0

I am new in using Java 8 date time API and was wondering how can i able to calculate the age in decimals which returns the double value like 30.5 which means 30 years and 6 months? For example the below sample code gets me the output as 30.0 but not 30.5 which probably am trying for.

LocalDate startDate = LocalDate.of(1984, Month.AUGUST, 10);
LocalDate endDate = LocalDate.of(2015, Month.JANUARY, 10);

double numberOfYears = ChronoUnit.YEARS.between(startDate, endDate);

System.out.println(numberOfYears); //Getting output as 30.0 but not 30.5 
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
Sam
  • 127
  • 2
  • 15
  • What have you tried? Did you read the Javadoc for `LocalDate` and maybe write some test cases? – Roddy of the Frozen Peas Oct 28 '17 at 02:02
  • I just posted my sample code up which i was trying to make it work – Sam Oct 28 '17 at 02:09
  • @RoddyoftheFrozenPeas Yes have read the javadoc for LocalDate but have not found any useful information relation to my issue. – Sam Oct 28 '17 at 02:17
  • 3
    By the way, using decimals in this fashion for date-time handling proves awkward and impractical. Check out the [standard ISO 8601 formats](https://en.wikipedia.org/wiki/ISO_8601#Durations) for representing spans of time as text. The standard formats are supported by default in the java.time classes when parsing/generating strings. – Basil Bourque Oct 28 '17 at 04:17

1 Answers1

3

The JavaDoc for ChronoUnit's between method clearly states:

The calculation returns a whole number, representing the number of complete units between the two temporals.

So you can't get 30.5 by just querying for years between. It only will give you the whole number -- 30.

But what you can do is get the months and divide by 12. For greater precision, you could instead use days, or even smaller units.

LocalDate startDate = LocalDate.of(1984, Month.AUGUST, 10);
LocalDate endDate = LocalDate.of(2015, Month.JANUARY, 10);

double numberOfMonths = ChronoUnit.MONTHS.between(startDate, endDate) / 12.0;
System.out.println(numberOfMonths); // prints 30.416666666666668

(If your endDate was February 10, 2015, then it prints 30.5....)

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
  • Oops you are right I should have read that carefully in javadocs as it returns the whole number but not the decimal. Thank you so much for your quick help as your proposed solution works!!! – Sam Oct 28 '17 at 02:28