5

我正在尝试根据用户的出生日期来获取用户的年龄。出生日期以 XML 中的字符串形式给出,并转换为Calendar如下形式:

final Calendar dob = javax.xml.bind.DatatypeConverter.parseDate(value);

然后我像这样计算用户的年龄:

final Calendar now = Calendar.getInstance();
int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
  --age;
}

我今天发现,如果今天是用户的生日(把派对帽收起来,这不是我的),年龄就太小了一岁。也就是说,如果用户出生于 2000 年,今天是她的生日,她应该是 14 岁,而不是 13 岁。但归根结底,Java 似乎有 DAY_OF_YEAR 错误:

System.out.println(String.format("Today: %d-%d; Birthday: %d-%d", now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH), dob.get(Calendar.MONTH), dob.get(Calendar.DAY_OF_MONTH)));
// prints: Today: 9-22; Birthday: 9-22
System.out.println(String.format("Today: %d; Birthday: %d", now.get(Calendar.DAY_OF_YEAR), dob.get(Calendar.DAY_OF_YEAR)));
// prints: Today: 295; Birthday: 296

是什么赋予了?

4

2 回答 2

8

边缘条件导致问题。

2000有什么特别之处?

这是闰年。

    Calendar cal = new GregorianCalendar();
    cal.set(2000, 11, 31);
    System.out.println(cal.getTime());
    System.out.println(cal.get(Calendar.DAY_OF_YEAR));

输出:

2000 年 12 月 31 日星期日 13:43:28 EST
366

2 月 29 日之后的所有内容都会被 1 抵消,特别是对于闰年。因此,这没有错。事实上,它按预期工作。

相反,您应该比较月份和日期来解决这个问题。

于 2014-10-22T17:41:32.473 回答
0

使用乔达

DateTime jodaDob = new DateTime(dob);
DateTime now = new DateTime();
if (jodaDob.isAfter(now)) {
    age = age - 1;
}

java.util.Date 在 joda 处理的极端情况下有许多错误。

于 2014-10-22T17:43:34.777 回答