Friday, April 3, 2009

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;

}