开发者

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

This question already has answers here: 开发者_如何学Go How do I calculate someone's age in Java? (28 answers) Closed 9 years ago.

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.


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

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 time as suggested by Jon Skeet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜