我想计算用户年龄,如果出生月份等于当前月份且出生日期小于或等于当天(如果用户输入他的话),我的方法不会给出正确的年龄出生日期通过日期选择器为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;
}
答案 0 :(得分:4)
您的代码存在两个问题:
dob.set(1990,3,9)
,因为月份开始于0 ==&gt;你可能需要dob.set(year, month - 1, day);
这似乎有效,但您应该使用各种方案进行测试,并确保您对结果感到满意:
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
}
答案 1 :(得分:-2)
例如,您可以通过转换两个日期(以毫秒为单位)和比Date对象来计算差异。代码将是这样的:
long ageMilis = today.getTimeInMillis() - dob.getTimeInMillis();
Date age = new Date(ageMilis);
return age.toString();