I have a string in the form of YYYY-MM-DDThh:mm:ss, which was extracted from an xml file.
This string represents a date of birth.
How can I find the person's age in years(integer) using java?
I have a string in the form of YYYY-MM-DDThh:mm:ss, which was extracted from an xml file.
This string represents a date of birth.
How can I find the person's age in years(integer) using java?
Given with the specific date format, the age can be calculated as following:
public class AgeCalculator {
public static int calculateAge(Date birthdate) {
Calendar birth = Calendar.getInstance();
birth.setTime(birthdate);
Calendar today = Calendar.getInstance();
int yearDifference = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) < birth.get(Calendar.MONTH)) {
yearDifference--;
} else {
if (today.get(Calendar.MONTH) == birth.get(Calendar.MONTH)
&& today.get(Calendar.DAY_OF_MONTH) < birth.get(Calendar.DAY_OF_MONTH)) {
yearDifference--;
}
}
return yearDifference;
}
public static void main(String[] args) throws ParseException {
// date format yyyy-MM-dd'T'HH:mm:ss
String birthdateStr = "2013-07-09T12:17:58-04:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date birthdate = df.parse(birthdateStr);
System.out.println(AgeCalculator.calculateAge(birthdate));
}
}