你如何在 Java 中减去日期?

问题描述:

在不得不如此深入地减去两个日期以计算天数跨度后,我的心在流血:

My heart is bleeding internally after having to go so deep to subtract two dates to calculate the span in number of days:

    GregorianCalendar c1 = new GregorianCalendar();
    GregorianCalendar c2 = new GregorianCalendar();
    c1.set(2000, 1, 1);
    c2.set(2010,1, 1);
    long span = c2.getTimeInMillis() - c1.getTimeInMillis();
    GregorianCalendar c3 = new GregorianCalendar();
    c3.setTimeInMillis(span);
    long numberOfMSInADay = 1000*60*60*24;
    System.out.println(c3.getTimeInMillis() / numberOfMSInADay); //3653

在 .NET 或您命名的任何现代语言中只有 2 行代码.

where it's only 2 lines of code in .NET, or any modern language you name.

这是java的残暴吗?或者有什么我应该知道的隐藏方法?

Is this atrocious of java? Or is there a hidden method I should know?

在util中使用Date类可以代替GregorianCalendar吗?如果是这样,我应该注意 1970 年这样的微妙事物吗?

Instead of using GregorianCalendar, is it okay to use Date class in util? If so, should I watch out for subtle things like the year 1970?

谢谢

这确实是标准 Java API 中最大的史诗般的失败之一.有一点耐心,然后您将获得具有 JSR 310/ThreeTen 指定的新日期和时间 API 的解决方案(最有可能)将包含在即将推出的 Java 8 中.

It's indeed one of the biggest epic failures in the standard Java API. Have a bit of patience, then you'll get your solution in flavor of the new Date and Time API specified by JSR 310 / ThreeTen which is (most likely) going to be included in the upcoming Java 8.

在那之前,您可以使用 JodaTime.

Until then, you can get away with JodaTime.

DateTime dt1 = new DateTime(2000, 1, 1, 0, 0, 0, 0);
DateTime dt2 = new DateTime(2010, 1, 1, 0, 0, 0, 0);
int days = Days.daysBetween(dt1, dt2).getDays();

顺便说一下,它的创建者 Stephen Colebourne 是 JSR 310 的幕后推手,所以它看起来非常相似.

Its creator, Stephen Colebourne, is by the way the guy behind JSR 310, so it'll look much similar.