本文介绍了你如何在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

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?

而不是使用GregorianCalendar,可以在util中使用Date类吗?如果是这样,我应该注意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中最大的史诗故障之一。有一点耐心,那么你会得到你的解决方案的新的日期和时间API 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.

在此之前,您可以通过。

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.

这篇关于你如何在Java中减去日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 12:51