Reputation: 39
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MM/dd");
String birthDate = format3.format(date);
try {
age = format3.parse(birthDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
if(age != null)
c.setTime(age);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date2 = c.get(Calendar.DATE);
LocalDate l1 = LocalDate.of(year,month,date2);
LocalDate now = LocalDate.now();
Period diff = Period.between(l1,now);
Integer age = diff.getYears();
String ageString = age.toString();
Upvotes: 1
Views: 215
Reputation: 1460
This would be my approach using LocalDate and DateTimeFormatter. It is not only shorter, but also less error-prone.
String inputDate = "1990/01/21";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate age = LocalDate.parse(inputDate, formatter);
Period diff = Period.between(age, LocalDate.now()); // outputs: 31 years
Upvotes: 1