开发者

How can I calculate the age at death? [duplicate]

This question already has answers here: 开发者_开发技巧 Closed 11 years ago.

Possible Duplicates:

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());
}

How can i calculate the age of death from the above. I dont want to use any externallibraries

EDIT: please look at what I've got so far.none of the other threads are like mine. most of them are about date from DOB to today and not in the format im using.


Try this:

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);
      }

}


You can solve this without converting them to strings. since the getDateOfBirth and getDateOfDeath return date objects, you can use the .getTime() method on them which Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

A fairly simple way of doing this could be
long millisecondsDiff = petDetails.getDateOfDeath().getTime - petDetails.getDateOfBirth().getTime;

You can then either create a new date object directly from this long, or you can do the proper calculations to change milliseconds into days. ie
long age = millisecondsDiff / (1000 * 60* 60 * 24);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜