直接上代码:
/** * 根据出生日期,计算用户年龄 * @param birthDay * @return */ 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; }
转自:https://blog.csdn.net/sunnyljs/article/details/80934685
标签:Java,get,int,MONTH,birthDay,cal,出生日期,年龄,Calendar From: https://www.cnblogs.com/Daniel-Leung/p/getagebybirthday202210228155030.html