方式一:时间戳速算
只适用于计算1970-01-01 08:00:00及之后出生的
// 1971-01-01 08:00:00的时间戳
private static final long TIME = 31536_000_000L;
public Integer getAge(Long birth) {
if (birth == null) {
return null;
}
Long now = System.currentTimeMillis();
if (birth > now) {
return 0;
}
if (birth > 0) {
Double age = Math.ceil((now - birth) / TIME);
return age.intValue();
}
return null;
}
方式二:年月日计算
public int getAge(Date birth) {
Calendar cal = Calendar.getInstance();
int thisYear = cal.get(Calendar.YEAR);
int thisMonth = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birth);
int birthYear = cal.get(Calendar.YEAR);
int birthMonth = cal.get(Calendar.MONTH);
int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int age = thisYear - birthYear;
// 未足月
if (thisMonth <= birthMonth) {
// 当月
if (thisMonth == birthMonth) {
// 未足日
if (dayOfMonth < birthdayOfMonth) {
age--;
}
} else {
age--;
}
}
return age;
}