I have date of birth and can get the current date.
In java, how can I calculate someone's age while taking leap year into account?
Edit: Can I use unix timestamps and compare the difference?
I have date of birth and can get the current date.
In java, how can I calculate someone's age while taking leap year into account?
Edit: Can I use unix timestamps and compare the difference?
As you may know that java 8 date and time API changes are inspired from Jodatime library itself, so out next solution using java 8 looks almost similar to above code sample:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
//Now access the values as below
System.out.println(p.getDays());
System.out.println(p.getMonths());
System.out.println(p.getYears());
LocalDate birthdate = new LocalDate (1990, 12, 2);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
In Java 8
:
LocalDate startDate = LocalDate.of(1987, Month.AUGUST, 10);
LocalDate endDate = LocalDate.of(2015, Month.MAY, 27);
long numberOfYears = ChronoUnit.YEARS.between(startDate, endDate);
Great examples for using dates with Java 8
:
Java 8 Date Examples
As @MadProgrammer has suggested, you could use JodaTime
.
Here's the sample code.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
What about:
Date birthDate = new Date(85, 03, 24);
GregorianCalendar birth = new GregorianCalendar();
birth.setTime(birthDate);
int month = birth.get(GregorianCalendar.MONTH);
int day = birth.get(GregorianCalendar.DAY_OF_MONTH);
GregorianCalendar now = new GregorianCalendar();
int age = now.get(GregorianCalendar.YEAR) - birth.get(GregorianCalendar.YEAR);
int birthMonth = birth.get(GregorianCalendar.MONTH);
int birthDay = birth.get(GregorianCalendar.DAY_OF_MONTH);
int nowMonth = now.get(GregorianCalendar.MONTH);
int nowDay = now.get(GregorianCalendar.DAY_OF_MONTH);
if (nowMonth>birthMonth) {
age = age+1;
} else {
if (nowMonth == birthMonth) {
if (nowDay >= birthDay) {
age= age+1;
}
}
}
System.out.println("Now it is my " + age+ " year of life");