如何计算Java中2个日期之间的年和月年龄 [英] How to calculate age in year and month between 2 dates in Java

查看:1751
本文介绍了如何计算Java中2个日期之间的年和月年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,如果有人帮助我,我会很感激。

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

当我尝试使用以下来源计算年龄时,它并没有给我我想要的价值。例如:date-> 29/12/2010,dob-> 30/12/1992,它会给我18而不是17.
有没有什么方法我可以编码返回我17yrs 11个月基于超过2个日期而不是18个月0日?

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;
    }

谢谢。

推荐答案

您可以使用 Joda Time 并计算期间介于两个 LocalDate 值之间(这是你在这里得到的),以月和年为单位。

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.

示例代码:

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

一般来说,Joda Time比使用日期/日历要好得多 - 而且你真的不想如果可以避免,就自己开始进行日期计算。它很快就会变得混乱。

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.

根据aioobe的回答,如果划分两个整数表达式,算术将以整数运算执行,这可能不是你想要的 - 但是对于日期和时间算术,只要让其他人在第一时间做艰苦的工作:)

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

上面的代码将使用ISO-8601日历,基本上是阳历。如果你想使用别的东西,在 LocalDate 的年/月/日之后将它指定为另一个构造函数参数。

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.

这篇关于如何计算Java中2个日期之间的年和月年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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