Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 662
blueberry Avatar asked Mar 21 '11 14:03

blueberry


People also ask

How do you calculate years difference in Java?

Using Joda-Time: Once you have the LocalDate, you can use Months. monthsBetween() and Years. yearsBetween() method to calcualte the number of months and years between two dates in Java. LocalDate jamesBirthDay = new LocalDate(1955, 5, 19); LocalDate now = new LocalDate(2015, 7, 30); int monthsBetween = Months.

What is period between in Java?

The between() method of Period class in Java is used to obtain a period consisting of the number of years, months, and days between two given dates (including start date and excluding end date).

How do I get an age from LocalDate?

LocalDate birthdate = new LocalDate (1970, 1, 20); LocalDate now = new LocalDate(); Years age = Years. yearsBetween(birthdate, now);


1 Answers

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.

like image 158
Jon Skeet Avatar answered Oct 05 '22 13:10

Jon Skeet