如何计算两个日期之间的年数差异? [英] How do I calculate the number of years difference between 2 dates?
问题描述
如何计算Java中两个日历之间的年数差异?
How do I calculate the number of years difference between 2 calendars in Java?
推荐答案
首先,您需要确定哪个比另一个年龄大.然后利用 while
循环,在其中测试旧版本是否不是 <代码> Calendar#add() 和一个( 1
)
First you need to determine which one is older than the other. Then make use of a while
loop wherein you test if the older one isn't after()
the newer one. Invoke Calendar#add()
with one (1
) Calendar.YEAR
on the older one to add the years. Keep a counter to count the years.
开球示例:
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
也就是说,Java SE中的 Date
和 Calendar
API实际上是史诗般的失败.正在为即将到来的Java 8计划新的Date API,即 JSR-310 这与 Joda-Time 非常相似.到目前为止,您可能要考虑Joda-Time,因为它确实可以简化这样的日期/时间计算/修改.这是使用Joda-Time的示例:
That said, the Date
and Calendar
API's in Java SE are actually epic failures. There's a new Date API in planning for upcoming Java 8, the JSR-310 which 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:
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
更简洁明了,不是吗?
这篇关于如何计算两个日期之间的年数差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!