出生日期,計算年齡工具類
阿新 • • 發佈:2021-08-29
/** * <p>年齡計算工具類</p> * * @author wangjs34383 * @date 2020/12/23 */ public class BirthdayUtil { public static int getAgeByBirth(Date birthDay) throws ParseException { int age = 0; 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); //計算整歲數 age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { //當前日期在生日之前,年齡減一 if (dayOfMonthNow < dayOfMonthBirth) { age--; } } else { //當前月份在生日之前,年齡減一 age--; } } return age; } }