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;

}



As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles