GWT Client Side Date / Calculate Age

Because GWT doesn't support the Calendar class on the client side (as of 1.6.3), getting the parts of the current date can be accomplished like this:

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;

}

3 comments:

  1. There is a small error. But anyway thank you very much for the algorithm. It is useful to me.

    try it on dates dob= 18.04.2008
    and today 16.04.2009

    IF does not work. You need use "int" instead "Integer"

    ReplyDelete
  2. That is a good point. I should have used currentMonth.equals(dobMonth) or changed the type to "int".

    Thanks for pointing that out!

    ReplyDelete
  3. public static int getAge(Date dateOfBirth) {

    int 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;

    }

    ReplyDelete