2011-03-04 43 views
0

可能重复:
How can I calculate the age of a person in year, month, days?
How can I calculate the difference between two dates我如何计算死亡时的年龄?

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); 
if(petDetails.getDateOfDeath() != null){ 
    String formatedDateOfDeath = formatter.format(petDetails.getDateOfDeath()); 
    String formateDateOfBirth = formatter.format(petDetails.getDateOfBirth()); 
} 

我怎么能计算出死亡年龄从上面。我不想使用任何外部库

编辑:请看看我到目前为止。没有其他线程就像我的。他们中的大多数是关于从DOB到今天的日期,而不是我使用的格式。

+0

可能重复的[我如何计算一个人在年,月,日的年龄?](http://stackoverflow.com/questions/453208/how-can-i-calculate-the-age-of -a人 - 在 - 年 - 月 - 日)。另见[这个答案](http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c/11942#11942)。 – 2011-03-04 15:15:00

+0

或http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – 2011-03-04 15:17:22

+4

从一小时前他的上一个问题的可能重复:http://stackoverflow.com/questions/5194216 /如何计算两个日期之间的差异关闭 – Riggy 2011-03-04 15:17:25

回答

0

试试这个:

public class Age { 

public static void main(String[] args) { 
     Calendar birthDate = new GregorianCalendar(1979, 1, 1); 
     Calendar deathDate = new GregorianCalendar(2011, 1, 1); 
     int age = deathDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR); 
     if ((birthDate.get(Calendar.MONTH) > deathDate.get(Calendar.MONTH)) 
      || (birthDate.get(Calendar.MONTH) == deathDate.get(Calendar.MONTH) && birthDate.get(Calendar.DAY_OF_MONTH) > deathDate 
       .get(Calendar.DAY_OF_MONTH))) { 
      age--; 
     } 
     System.out.println(age); 
     } 

}

+0

它与我想要的不一样。我想要放在ca地领域ddude! – code511788465541441 2011-03-04 15:22:13

+0

getDateOfBirth返回什么?它是一个日期对象吗? – Mike 2011-03-04 15:23:02

+0

@Mike是的,它是日期。 – code511788465541441 2011-03-04 15:24:37

0

就可以解决这个不用它们转换为字符串。由于getDateOfBirth和getDateOfDeath归期对象 ,您可以使用.getTime()方法对它们其中Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

这样做的一个相当简单的方式可能是
长millisecondsDiff = petDetails.getDateOfDeath()的getTime - petDetails .getDateOfBirth()的getTime。

然后,您可以直接从此长时间创建新的日期对象,也可以执行正确的计算以将毫秒更改为几天。即
long age = millisecondsDiff /(1000 * 60 * 60 * 24);

+0

只有在每年的秒数和天数完全相同的情况下,我们才能正确地工作,正如我们所知,这不正确,并可能导致我认为的边缘情况。 – Voo 2011-03-04 15:41:33

+0

从这个http://www.java2s.com/Code/Java/Development-Class/Computedaysbetween2dates.htm它看起来像他们添加一个小时的差异,然后再除以天。也许这对角落案件有帮助? – Mike 2011-03-04 15:48:47