【问题标题】:How can I calculate the age at death? [duplicate]如何计算死亡年龄? [复制]
【发布时间】:2011-03-04 15:12:17
【问题描述】:

可能的重复:
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());
}

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

编辑:请看看我到目前为止所得到的。其他线程都不像我的。其中大多数是关于从出生日期到今天的日期,而不是我使用的格式。

【问题讨论】:

标签: java


【解决方案1】:

试试这个:

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

}

【讨论】:

  • 它和我想要的不一样。伙计,我应该在日历字段中放什么!
  • getDateOfBirth 返回什么?它是一个日期对象吗?
【解决方案2】:

您无需将它们转换为字符串即可解决此问题。 由于 getDateOfBirth 和 getDateOfDeath 返回日期对象,您可以对它们使用 .getTime() 方法 Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

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

然后您可以直接从这个 long 创建一个新的日期对象,或者您可以进行适当的计算以将毫秒更改为天。即
long age = millisecondsDiff / (1000 * 60* 60 * 24);

【讨论】:

  • 只有在每年的秒数和天数完全相同的情况下才能正常工作,我们知道这不是真的,我认为可能会导致边缘情况。
  • 从这个java2s.com/Code/Java/Development-Class/…看来,他们在除以天之前会增加一小时的差异。也许这有助于解决极端情况?
猜你喜欢
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多