当前位置: 动力学知识库 > 问答 > 编程问答 >

Difference of Dates in Java in Years

问题描述:

This question already has an answer here:

  • How do I calculate someone's age in Java?

    25 answers

网友答案:

If you write long d=(1000*60*60*24*365);, the result of 1000*60*60*24*365 will be calculated as int, while this is too large for int type. You should use 1000l*60*60*24*365 to calculate this.

网友答案:

As well as issues mentioned in the comments above, this line causes a numeric overflow:

long d=(1000*60*60*24*365);

Remove that line, and use this instead; you'll get a roughly correct answer:

long years = Math.round(diff / 1000 / 60 / 60 / 24 / 365);
网友答案:

One different method.

public static int age(Date birthday, Date date) {
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    int d1 = Integer.parseInt(formatter.format(birthday));
    int d2 = Integer.parseInt(formatter.format(date));
    int age = (d2-d1)/10000;
    return age;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: