Java 如何计算两个日期之间的年数差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2846135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:33:04  来源:igfitidea点击:

How do I calculate the number of years difference between 2 dates?

java

提问by Scott Usher

How do I calculate the number of years difference between 2 calendars in Java?

如何计算 Java 中两个日历之间的年数差异?

回答by BalusC

First you need to determine which one is older than the other. Then make use of a whileloop wherein you test if the older one isn't after()the newer one. Invoke Calendar#add()with one (1) Calendar.YEARon the older one to add the years. Keep a counter to count the years.

首先,您需要确定哪个比另一个更老。然后利用一个while循环来测试旧的是否不是after()新的。Calendar#add()用一个 ( 1)调用Calendar.YEAR旧的以添加年份。保留一个计数器来计算年数。

Kickoff example:

开场示例:

Calendar myBirthDate = Calendar.getInstance();
myBirthDate.clear();
myBirthDate.set(1978, 3 - 1, 26);
Calendar now = Calendar.getInstance();
Calendar clone = (Calendar) myBirthDate.clone(); // Otherwise changes are been reflected.
int years = -1;
while (!clone.after(now)) {
    clone.add(Calendar.YEAR, 1);
    years++;
}
System.out.println(years); // 32


That said, the Dateand CalendarAPI's in Java SE are actually epic failures. There's a new Date API in planning for upcoming Java 8, the JSR-310which is much similar to Joda-Time. As far now you may want to consider Joda-Time since it really eases Date/Time calculations/modifications like this. Here's an example using Joda-Time:

也就是说,Java SE 中的DateCalendarAPI 实际上是史诗般的失败。有一个新的 Date API 正在为即将到来的 Java 8 做规划,JSR-310Joda-Time非常相似。到目前为止,您可能想要考虑 Joda-Time,因为它确实简化了像这样的日期/时间计算/修改。下面是一个使用 Joda-Time 的例子:

DateTime myBirthDate = new DateTime(1978, 3, 26, 0, 0, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
int years = period.getYears();
System.out.println(years); // 32

Much more clear and concise, isn't it?

更加简洁明了,不是吗?

回答by j-g-faustus

Or you could just use Calendar.getTimeInMillis():

或者你可以只使用Calendar.getTimeInMillis()

long msYear = 1000L * 60 * 60 * 24 * 365;
long msDiff = c2.getTimeInMillis() - c1.getTimeInMillis();
System.out.println("Years diff: " + String.valueOf(msDiff / msYear));

EditThis ignores leap years. But if you are looking for an integer representation of the number of years the leap years are irrelevant for periods shorter than half a millennium or so.

编辑这忽略了闰年。但是,如果您正在寻找年数的整数表示,则闰年与短于半个千年左右的时期无关。

This is plenty of exactness for calculating somebody's age, for example. But not accurate enough to tell their birthday.

例如,这对于计算某人的年龄来说非常准确。但不足以准确地说出他们的生日。

If you need your year difference more exact than to three significant digits within a human lifespan (approximately 80.00 years vs 80.05), you should use the "official" solution.

如果您需要比人类寿命(大约 80.00 年与 80.05 年)内三位有效数字更精确的年份差异,您应该使用“官方”解决方案。

If not, there's no particular reason to put in extra effort for a degree of precision you are not going to use.

如果没有,则没有特别的理由为您不打算使用的精确度付出额外的努力。

回答by Kevin

Calendar dobDate; // Set this to date to check
Calendar today = Calendar.getInstance();
int curYear = today.get(Calendar.YEAR);
int curMonth = today.get(Calendar.MONTH);
int curDay = today.get(Calendar.DAY_OF_MONTH);

int year = dobDate.get(Calendar.YEAR);
int month = dobDate.get(Calendar.MONTH);
int day = dobDate.get(Calendar.DAY_OF_MONTH);

int age = curYear - year;
if (curMonth < month || (month == curMonth && curDay < day)) {
    age--;
}

This avoids looping and should be accurate to the day.

这避免了循环并且应该准确到当天。

回答by Nihan Guner

double diff = d2.getTime() - d1.getTime();
double d = 1000 * 60 * 60 * 24 * 365;
return (int) Math.round(diff / d);

(java.lang.Math)

(java.lang.Math)