Hi Experts,
I want to calculate age, i.e. user enter the date of birth and the output would be the age.
I guess I should use GregorianCalendar. The logic is subtracting the user date from current date. But how? Can any one have any idea……………

Thanks in advance

6 Years
Discussion Span
Last Post by stephen84s

If you plan on using the Joda Time API, it is as simple as:-

How do I calculate the difference between two dates?

This question has more than one answer! If you just want the number of whole days between two dates, then you can use the new Days class in version 1.4 of Joda-Time.

Days d = Days.daysBetween(startDate, endDate);
  int days = d.getDays();

This method, and other static methods on the Days class have been designed to operate well with the JDK5 static import facility.

If however you want to calculate the number of days, weeks, months and years between the two dates, then you need a Period By default, this will split the difference between the two datetimes into parts, such as "1 month, 2 weeks, 4 days and 7 hours".

Period p = new Period(startDate, endDate);

You can control which fields get extracted using a PeriodType.

Period p = new Period(startDate, endDate, PeriodType.yearMonthDay());

This example will return not return any weeks or time fields, thus the previous example becomes "1 month and 18 days".

For more info, consult the period guide.

Source: http://joda-time.sourceforge.net/faq.html#datediff
Although I do feel it would be an overkill to use the Joda Time API just for this purpose.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.