How to calculate age in java using date?

2.40K viewsJava
0

how to calculate age in java using the date. I will pass the date of birth date, the code should return age.

Changed status to publish
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..!!

 

Changed status to publish
Add a Comment
Write your answer.