import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @ClassName: CalculateAge
* @Description: 根据生日计算年龄
* @Version 1.0
*/
public class CalculateAge {
public static Date parse(String strDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(strDate);
}
public static int getAge(Date birthDay) throws Exception {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) { //出生日期晚于当前时间,无法计算
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(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth; //计算整岁数
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前,年龄减一
} else {
age--;//当前月份在生日之前,年龄减一
}
}
return age;
}
}
计算年龄方法类
最新推荐文章于 2023-07-06 15:38:33 发布