Java 8 Date time for calculating age in decimals [duplicate]

梦想的初衷 提交于 2020-12-26 05:07:04

问题


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 

回答1:


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....)



来源:https://stackoverflow.com/questions/46985522/java-8-date-time-for-calculating-age-in-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!