public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
And For Calculating the exact age call :-
getExactAge("01/01/1988","12/10/2012");
public static String getExactAge(String birthDate, String tillDate) {
StringBuffer returnValue = new StringBuffer("");
int nYear, nMonth, nDay = 0;
String sYear, sMonth, sDay = "";
try {
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
long birthday = dateFormatter.parse(birthDate).getTime();
long today = dateFormatter.parse(tillDate).getTime();
Calendar age = Calendar.getInstance(Locale.getDefault());
age.setTime(new Date(Math.abs(today - birthday)));
nYear = age.get(Calendar.YEAR) - 1970;
nMonth = age.get(Calendar.MONTH);
nDay = age.get(Calendar.DAY_OF_MONTH);
sYear = (nYear > 0 ? nYear + " year" + (nYear > 1 ? "s" : "")
+ ", " : "");
sMonth = (nMonth > 0 ? nMonth + " month" + (nMonth > 1 ? "s" : "")
+ ", " : "");
sDay = (nDay > 0 ? nDay + " day" + (nDay > 1 ? "s" : "") : "");
if ((today - birthday) > 0) {
returnValue.append(sYear);
returnValue.append(sMonth);
returnValue.append(sDay);
} else {
returnValue.append("Not born yet !");
}
} catch (Exception e) {
returnValue.append("Exception occured");
}
return returnValue.toString();
}
No comments:
Post a Comment