Java如何计算年/月/年的年龄?

时间:2013-02-28 06:22:55

标签: java date calendar

如何计算17/08/199218/06/2013之间的年龄(day/month/year

我想要结果日月份

2 个答案:

答案 0 :(得分:3)

这似乎有效

    GregorianCalendar d1 = new GregorianCalendar(1992, 8 - 1, 17);
    GregorianCalendar d2 = new GregorianCalendar(2013, 6 - 1, 18);

    d2.add(Calendar.YEAR, -d1.get(Calendar.YEAR));
    d2.add(Calendar.MONTH, -d1.get(Calendar.MONTH));
    d2.add(Calendar.DAY_OF_MONTH, -d1.get(Calendar.DAY_OF_MONTH) + 1);

    int y = d2.get(Calendar.YEAR);
    int m = d2.get(Calendar.MONTH);
    int d = d2.get(Calendar.DAY_OF_MONTH) - 1;

答案 1 :(得分:0)

虽然我不应该回答这个问题,但在看到你对@Harry Joy的评论回复之后我已经回答了这个问题:P

Date date1 = new SimpleDateFormat("dd/MM/yyyy").parse(dateOfBirth);
Date date2 = new SimpleDateFormat("dd/MM/yyyy").parse(currentDate);
cal1.setTime(date1);
cal2.setTime(date2);
if(cal2.get(Calendar.DAY_OF_YEAR) < cal1.get(Calendar.DAY_OF_YEAR)) {
      factor = -1; 
}
age = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR) + factor;
System.out.println("Your age is: "+age);