用util包下的Calender类来计算
public static Integer getAge(String birthday) throws Exception{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date birth = df.parse(birthday);
Calendar now = Calendar.getInstance();
Calendar born = Calendar.getInstance();
now.setTime(new Date());
born.setTime(birth);
if(born.after(now)){
throw new IllegalArgumentException("Can't be born in the future");
}
int age = now.get(Calendar.YEAR)-born.get(Calendar.YEAR);
if(now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age -= 1;
}
return age;
}
网友评论