首页 > 代码库 > 根据生日计算年龄
根据生日计算年龄
/*
* 根据生日计算年龄
*/
public int age(String birthDate) {
SimpleDateFormat dft=new SimpleDateFormat("yyyy-MM-dd");
Date time = null;
//类型转换
try {
time=dft.parse(birthDate);
} catch (ParseException e1) {
e1.printStackTrace();
}
//获取当前系统时间
Calendar cal = Calendar.getInstance();
//如果生日大于当前系统时间,则抛出异常
if(cal.before(time)){
throw new IllegalArgumentException(
"The birthDay is before Now.It‘s unbelievable!");
}
//取出系统当前时间的年月日
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow= cal.get(Calendar.DAY_OF_MONTH);
//将日期设置为出生日期
cal.setTime(time);
//取出出生时的年月日
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
//计算age
int age = 0;
age=yearNow - yearBirth;
if(monthNow<=monthBirth){
if(monthNow==monthBirth){
if(dayOfMonthNow<dayOfMonthBirth){
age--;
}
}else{
age--;
}
}
return age;
}
根据生日计算年龄