java 小数计算,Java 8日期时间,以小数形式计算年龄

这篇博客讨论了如何利用Java 8的日期时间API计算带有小数部分的年龄,例如30.5年,意味着30年6个月。通过获取月份数量并除以12,可以得到更精确的年龄值。示例代码展示了如何从两个日期之间计算出精确到月的年龄,并指出只查询年份无法得到带有小数的年龄结果。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,计算两个日期相差多少月可以使用Java 8的新日期时间API。首先需要使用LocalDate类将日期转换为本地日期对象,然后使用Period类计算两个日期之间的差距。由于Period类返回的是整数值,因此需要在计算月份时使用BigDecimal类以精确小数的方式进行计算。 以下是一个示例代码,它计算了2019年1月1日和2021年7月1日之间的月份差距: ``` import java.time.LocalDate; import java.time.Period; import java.math.BigDecimal; public class MonthDiff { public static void main(String[] args) { LocalDate date1 = LocalDate.of(2019, 1, 1); LocalDate date2 = LocalDate.of(2021, 7, 1); Period diff = Period.between(date1, date2); BigDecimal months = BigDecimal.valueOf(diff.toTotalMonths()).add( BigDecimal.valueOf(diff.getDays()).divide(BigDecimal.valueOf(date2.lengthOfMonth()))); System.out.println("The difference in months is " + months); } } ``` 以上代码计算结果为31.6个月。具体计算方法是:先使用Period类将两个日期之间的差距计算出来,然后使用toTotalMonths()方法获取两个日期之间的总月份数,接着使用BigDecimal类将余下来的天数除以第二个日期所在月份的天数,得出月份数的小数部分,并将其加到整数月份数中。最终得出的结果以BigDecimal类型输出,保留小数点后一位。 需要注意的一点是,这种计算方法可能不够准确,因为它假设每个月都是精确的30天。如果需要更精确的计算,需要考虑每个月的实际天数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值