1:修改BUG
This commit is contained in:
@@ -258,4 +258,43 @@ public class TimeUtils {
|
||||
return "1天"; // 或者 return "0天";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据生日字符串计算年龄
|
||||
* @param birthDay 生日字符串,格式为 "yyyy-MM-dd"
|
||||
* @return 年龄
|
||||
*/
|
||||
public static int getAgeByBirthDay(String birthDay) {
|
||||
if (birthDay == null || birthDay.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Date birthDate = sdf.parse(birthDay);
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
int currentYear = cal.get(Calendar.YEAR);
|
||||
int currentMonth = cal.get(Calendar.MONTH);
|
||||
int currentDay = cal.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
cal.setTime(birthDate);
|
||||
int birthYear = cal.get(Calendar.YEAR);
|
||||
int birthMonth = cal.get(Calendar.MONTH);
|
||||
int birthDayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
int age = currentYear - birthYear;
|
||||
|
||||
// 如果当前月份小于生日月份,或者月份相同但当前日期小于生日日期,则年龄减1
|
||||
if (currentMonth < birthMonth ||
|
||||
(currentMonth == birthMonth && currentDay < birthDayOfMonth)) {
|
||||
age--;
|
||||
}
|
||||
|
||||
return age < 0 ? 0 : age;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user