Closed sunyaf closed 1 month ago
假如生日是2008-07-11,当前时间2014-07-11,IdcardUtil.getAgeByIdCard 得出来是15岁 假如生日是2008-07-31,当前时间2014-07-31,IdcardUtil.getAgeByIdCard 得出来是16岁
为什么是这个逻辑呢
protected static int age(long birthday, long dateToCompare) { if (birthday > dateToCompare) { throw new IllegalArgumentException("Birthday is after dateToCompare!"); } else { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(dateToCompare); int year = cal.get(1); int month = cal.get(2); int dayOfMonth = cal.get(5); boolean isLastDayOfMonth = dayOfMonth == cal.getActualMaximum(5); cal.setTimeInMillis(birthday); int age = year - cal.get(1); int monthBirth = cal.get(2); if (age == 0) { return 0; } else { if (month == monthBirth) { int dayOfMonthBirth = cal.get(5); boolean isLastDayOfMonthBirth = dayOfMonthBirth == cal.getActualMaximum(5); if ((!isLastDayOfMonth || !isLastDayOfMonthBirth) && dayOfMonth <= dayOfMonthBirth) { --age; } } else if (month < monthBirth) { --age; } return age; } } }
你是不使用了旧版本的Hutool导致的问题?
的出来的都是5岁。
假如生日是2008-07-11,当前时间2014-07-11,IdcardUtil.getAgeByIdCard 得出来是15岁 假如生日是2008-07-31,当前时间2014-07-31,IdcardUtil.getAgeByIdCard 得出来是16岁
为什么是这个逻辑呢