how to calculate age in java using the date. I will pass the date of birth date, the code should return age.
Manohar Changed status to publish June 16, 2019
Snippet:
public int getAge(Date dateOfBirth) {
int age = 0;
if (dateOfBirth != null) {
Calendar cal = new GregorianCalendar();
cal.setTime(dateOfBirth);
Calendar now = new GregorianCalendar();
now.setTime(new Date());
age = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH))) {
age--;
}
}
return age;
}
I hope the above snippet works fine, please try..!!
Manohar Changed status to publish June 17, 2019
