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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5378913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:51:20  来源:igfitidea点击:

How to calculate age in year and month between 2 dates in Java

java

提问by blueberry

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?

当我尝试使用以下来源计算年龄时,它没有给出我想要的值。例如: date->29/12/2010 , dob->30/12/1992 ,它会给我 18 而不是 17. 有没有什么方法可以让我根据上述 2 个日期返回 17yrs 11mths 18yrs0mths?

public double getAgeAsOf( Date date ) {
        return ((date.getTime() - dob.getTime())/(1000*60*60*24))/365;
    }

Thanks.

谢谢。

回答by Jon Skeet

You can use Joda Timeand compute a Periodbetween two LocalDatevalues (which is what you've got here) using months and years as the units.

您可以使用Joda Time并使用月和年作为单位计算Period两个LocalDate值之间的a (这是您在此处获得的)。

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.

一般来说,Joda Time 是一个比使用日期/日历更好的 API - 如果可以避免的话,您真的不想参与自己执行日期计算的业务。它很快就会变得混乱。

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

根据 aioobe 的回答,如果您将两个整数表达式相除,则算术将以整数算术执行,这可能不是您想要的 - 但对于日期和时间算术,首先让其他人完成艰苦的工作:)

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.

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

回答by aioobe

You have a few problems with your code:

您的代码有一些问题:

  1. You're doing integer division, which truncates the result to the closest lower integer.

    For example, if you divide 729 by 365 you'll get 1 (and you've lost the fractional part, which you would need when calculating months etc)

  2. Another problem is that you're using 365 days for one year, while it is actually closer to 365.25 (when including extra days due to leap years).

  1. 您正在执行整数除法,它将结果截断为最接近的较低整数。

    例如,如果您将 729 除以 365,您将得到 1(并且您已经丢失了计算月份等时需要的小数部分)

  2. 另一个问题是,您一年使用 365 天,而实际上更接近 365.25(包括由于闰年造成的额外天数)。

Here's a slightly improved snippet of code:

这是一个稍微改进的代码片段:

import java.util.Date;

public class Test {

    static double msPerGregorianYear = 365.25 * 86400 * 1000;

    static Date dob = new Date(1992, 12, 30);

    public static double getAgeAsOf(Date date) {
        return (date.getTime() - dob.getTime()) / msPerGregorianYear;
    }

    public static void main(String[] args) {

        double years = getAgeAsOf(new Date(2010, 12, 29));

        // years == 17.99315537303217

        int yy = (int) years;
        int mm = (int) ((years - yy) * 12);

        // Prints   "17 years and 11 moths."
        System.out.printf("%d years and %d moths.", yy, mm);
    }
}

If you're ever doing anything more complicated than figuring out the number of years given the number of milliseconds, I suggest you turn to some time-library such as Joda timeas suggested by Jon Skeet.

如果您做过比根据毫秒数计算年数更复杂的事情,我建议您转向一些时间库,例如Jon Skeet 建议的Joda 时间