How to calculate age in java using date?

3.63K viewsJava
0

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
Add a Comment
1

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
Add a Comment
Write your answer.