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
解决方案
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....)