Possible Duplicate:
How do I calculate someone's age in Java?
我想计算用户年龄,如果出生月份等于当前月份并且出生日期小于或等于当前日期(如果用户输入他的年龄),我的方法不会给出正确的年龄通过日期选择器输入出生日期为 9/4/1990 或 4/4/1990 年龄将为 21 岁而不是 22 岁)我该如何解决这个问题?在这种情况下,我应该做什么更新才能获得正确的年龄?请帮助我....
这是我的方法
public static String getAge(int year,int month,int day) {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
最佳答案
您的代码有两个问题:
- 如果出生日期是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
}
关于java - 年龄计算方法不能返回正确的年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10066633/