I use this code when calculating age (in years):
String datetext = "10-29-1977"; // Date in text
try {
Calendar birth = new GregorianCalendar();
Calendar today = new GregorianCalendar();
int age = 0;
int factor = 0; //to correctly calculate age when birthday has not been yet celebrated
Date birthDate = new SimpleDateFormat("MM-dd-yy
Date currentDate = new Date(); //current date
birth.setTime(birthDate);
today.setTime(currentDate)
// check if birthday has been celebrated this year
if(today.get(Calendar.DAY_
factor = -1; //birthday not celebrated
}
age = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + factor;
System.out.println("AGE (years): "+age);
} catch (ParseException e) {
System.out.println("Given date: "+datetext+ " not in expected format (Please enter a MM-DD-YYYY date)");
}
Main Topics
Browse All Topics





by: Ajay-SinghPosted on 2007-10-24 at 10:07:32ID: 20140811
You can use the following
yy").parse (text); s() - 1000);
String text = // Date in text
Date date = new SimpleDateFormat("MM-dd-yy
int age = (int) (System.currentTimeInMilli
date.getTime())/(24*60*60*