您的代码有两个问题:
- 如果出生日期是 1990 年 4 月 9 日,你需要写成
dob.set(1990,3,9)月份从 0 开始 ==> 你可能需要dob.set(year, month - 1, day);
- 如果当年是闰年而不是出生年份(反之亦然)并且日期在 2 月 28 日/29 日之后,您将在同一日期获得 1 天的差异。
这似乎可行,但您应该使用各种场景对其进行测试,并确保您对结果感到满意:
public static String getAge(int year, int month, int day) {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month - 1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
age--;
} else if(today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)) {
if (today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {
age--;
}
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
还有一个(非常简化的)测试:
public static void main(String[] args) { //today = 8 April 2012
System.out.println(getAge(1990,3,7)); //22
System.out.println(getAge(1990,3,8)); //22
System.out.println(getAge(1990,3,9)); //22
System.out.println(getAge(1990,4,7)); //22
System.out.println(getAge(1990,4,8)); //22
System.out.println(getAge(1990,4,9)); //21
System.out.println(getAge(1990,5,7)); //21
System.out.println(getAge(1990,5,8)); //21
System.out.println(getAge(1990,5,9)); //21
}