java date 年龄,如何计算Java中2个日期之间的年和月年龄

I am a newbie and appreciate if someone help me out.

When I tried to calculate age using the below source , it does not give me the value of what I want . For example : date->29/12/2010 , dob->30/12/1992 , it will give me 18 instead of 17.

Is there any method that I can code to return me 17yrs 11mths based on the above 2 dates instead of 18yrs0mths?

public double getAgeAsOf( Date date ) {

return ((date.getTime() - dob.getTime())/(1000*60*60*24))/365;

}

Thanks.

解决方案

You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.

Sample code:

import org.joda.time.*;

public class Test {

public static void main(String[] args) {

LocalDate dob = new LocalDate(1992, 12, 30);

LocalDate date = new LocalDate(2010, 12, 29);

Period period = new Period(dob, date, PeriodType.yearMonthDay());

System.out.println(period.getYears() + " years and " +

period.getMonths() + " months");

}

}

(This uses a period type which includes days as well, but that won't affect the answer.)

In general, Joda Time is a much better API than using Date/Calendar - and you really don't want to get into the business of performing date calculations yourself if you can avoid it. It gets messy really quickly.

As per aioobe's answer, if you divide two integer expressions the arithmetic will be performed in integer arithmetic, which may not be what you want - but for date and time arithmetic, just let someone else do the hard work in the first place :)

The code above will use the ISO-8601 calendar by the way, which is basically the Gregorian calendar. If you want to use something else, specify it as another constructor argument after the year/month/day for LocalDate.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值