Java 8日期时间,以小数形式计算年龄 [英] Java 8 Date time for calculating age in decimals

查看:377
本文介绍了Java 8日期时间,以小数形式计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java 8日期时间API的新手,我想知道如何计算以十进制表示的年龄,该年龄返回像30.5这样的double值,这意味着30年零6个月?例如,下面的示例代码为我提供了30.0的输出,但不是30.5的输出(

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.

因此,仅通过查询之间的年份,您 不会获得30.5.它只会给您整个数字-30.

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

但是您可以做的是得到月份并除以12.要获得更高的精度,您可以改用几天甚至更小的单位.

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

(如果您的endDate是2015年2月10日,则打印30.5....)

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

这篇关于Java 8日期时间,以小数形式计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆