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.
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.
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).
LocalDate birthdate = new LocalDate (1970, 1, 20); LocalDate now = new LocalDate(); Years age = Years. yearsBetween(birthdate, now);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With