根据生日计算年龄的方法
***- //根据生日计算年龄的方法***
public static int birthdayToAge(String birthday) {
//思路:
Date nowDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//1.把字符串类型的生日转换成Date类型的生日
Date birthdayDate = null;
try {
birthdayDate = sdf.parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
//1.2判断日期是否合法
if (birthdayDate.after(new Date())){
//传入日期是否在当前日期之后,说明日期不合法
return -1;//标识
}
//2.获取当前时间的日历对象
Calendar cal = Calendar.getInstance();
//3.获得当前的年月日
int nowYear = cal.get(Calendar.YEAR);
int nowMonth = cal.get(Calendar.MONTH);
int nowDay = cal.get(Calendar.DAY_OF_MONTH);
//4.把Date类型的生日转换成日历对象
cal.setTime(birthdayDate);
//5.获取生日得年月日
int birthdayYear = cal.get(Calendar.YEAR);
int birthdayMonth = cal.get(Calendar.MONTH);
int birthdayDay = cal.get(Calendar.DAY_OF_MONTH);
//6.计算初步年龄:当前年份 减去 出生年份
int age = nowYear - birthdayYear;
//7.判断是否已经过生日:
if (nowMonth < birthdayMonth) {// 如果生日月份大于当前月份,那么初步年龄-1
age--;
}
if (nowMonth == birthdayMonth) {// 如果生日月份等于当前月份,并且生日的日期大于当前日期,那么初步年龄-1
if (nowDay < birthdayDay) {
age--;
}
}
//8.返回年龄
return age;
}