public static int getAge(Date birth) { Calendar cal = Calendar.getInstance(); int thisYear = cal.get(Calendar.YEAR); int thisMonth = cal.get(Calendar.MONTH); int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birth); int birthYear = cal.get(Calendar.YEAR); int birthMonth = cal.get(Calendar.MONTH); int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH); int age = thisYear - birthYear; // 未足月 if (thisMonth <= birthMonth) { // 当月 if (thisMonth == birthMonth) { // 未足日 if (dayOfMonth < birthdayOfMonth) { age--; } } else { age--; } } return age; }
时间: 2024-02-07 11:02:05 浏览: 110
下面是代码的简化版本:
```
public static int getAge(Date birth) {
Calendar cal = Calendar.getInstance();
cal.setTime(birth);
int birthYear = cal.get(Calendar.YEAR);
int birthMonth = cal.get(Calendar.MONTH);
int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int thisMonth = Calendar.getInstance().get(Calendar.MONTH);
int dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int age = thisYear - birthYear;
if (thisMonth <= birthMonth && thisMonth == birthMonth && dayOfMonth < birthdayOfMonth) {
age--;
} else {
age--;
}
return age;
}
```
这个简化版本将一些变量的声明和初始化放在了一起,同时将一些重复的代码进行了简化。
阅读全文