Date today = new Date();
Integer currentYear = new Integer(DateTimeFormat.getFormat("yyyy").format(today));
Integer currentMonth = new Integer(DateTimeFormat.getFormat("M").format(today));
Integer currentDay = new Integer(DateTimeFormat.getFormat("d").format(today));
Age calculating function:
public static int calculateAge(Date dob)
{
Date today = new Date();
Integer currentYear = new Integer(DateTimeFormat.getFormat("yyyy").format(today));
Integer currentMonth = new Integer(DateTimeFormat.getFormat("M").format(today));
Integer currentDay = new Integer(DateTimeFormat.getFormat("d").format(today));
Integer dobYear = new Integer(DateTimeFormat.getFormat("yyyy").format(dob));
Integer dobMonth = new Integer(DateTimeFormat.getFormat("M").format(dob));
Integer dobDay = new Integer(DateTimeFormat.getFormat("d").format(dob));
int age = currentYear - dobYear;
if((dobMonth > currentMonth) || (currentMonth == dobMonth && dobDay > currentDay))
age--;
return age;
}
There is a small error. But anyway thank you very much for the algorithm. It is useful to me.
ReplyDeletetry it on dates dob= 18.04.2008
and today 16.04.2009
IF does not work. You need use "int" instead "Integer"
That is a good point. I should have used currentMonth.equals(dobMonth) or changed the type to "int".
ReplyDeleteThanks for pointing that out!
public static int getAge(Date dateOfBirth) {
ReplyDeleteint age = 0;
DateTime dateOfBirth = new DateTime(this.dateOfBirth);
DateTime today = new DateTime();
age = today.getYear() - dateOfBirth.getYear();
if (dateOfBirth.getMonthOfYear() > today.getMonthOfYear())
age--;
else if (dateOfBirth.getMonthOfYear() == today.getMonthOfYear())
if (dateOfBirth.getDayOfMonth() > today.getDayOfMonth())
age--;
return age;
}