java 计算Java中的日期差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/453388/
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-10-29 12:27:03  来源:igfitidea点击:

Calculating difference in dates in Java

javadatedatetimedate-arithmetic

提问by Anirudh

I find it funny that Java (or the java.util library) does not have a built-in function to calculate difference in dates. I want to subtract one date from another to get the elapsed time between them. What is the best way to do this?

我觉得 Java(或 java.util 库)没有内置函数来计算日期差异很有趣。我想从另一个日期中减去一个日期以获得它们之间经过的时间。做这个的最好方式是什么?

I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, I wanted to know if this works in all cases (with daylight saving, etc.).

我知道简单的方法是以毫秒为单位的时间差,然后将其转换为天。但是,我想知道这是否适用于所有情况(夏令时等)。

采纳答案by Jason S

I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, i wanted to know if this works in all cases (with daylight saving, etc.).

我知道简单的方法是以毫秒为单位的时间差,然后将其转换为天。但是,我想知道这是否适用于所有情况(夏令时等)。

If your times are derived from UTC dates, or they are just the difference between two calls to System.getCurrentTimeMillis() measured on the same system, you will get a valid number of milliseconds as the difference, independent of any timezone issues. (which is why everything should be using UTC as a storage format -- it's much easier to go from UTC->local time; if you try to go the other way then you need to store the local timezone along with the local time -- or attempt to infer it, gack!)

如果您的时间来自 UTC 日期,或者它们只是在同一系统上测量的两次 System.getCurrentTimeMillis() 调用之间的差异,您将获得有效的毫秒数作为差异,与任何时区问题无关。(这就是为什么一切都应该使用 UTC 作为存储格式的原因——从 UTC-> 本地时间开始要容易得多;如果你尝试相反的方式,那么你需要将本地时区与本地时间一起存储——或尝试推断它,gack!)

As for turning this into a number of days, you should just be able to divide by 86400000... with the caveat that there is an occasional leap secondevery other year or so.

至于把它变成天数,你应该只能除以 86400000 ......但需要注意的是每隔一年左右偶尔会有一个闰秒

回答by duffymo

Java's not missing much, if you look at open source: try Joda-Time.

如果您查看开源,Java 并没有遗漏太多:尝试Joda-Time

回答by Basil Bourque

Use either Joda-Time or the new java.time package in Java 8.

在 Java 8 中使用 Joda-Time 或新的 java.time 包。

Both frameworks use the Half-Openapproach where the beginning is inclusivewhile the ending is exclusive. Sometimes notated as [). This is generally the best approach for defining spans of time.

这两个框架都使用半开放方法,其中开始是包容性的,而结束是独占性的。有时记为[). 这通常是定义时间跨度的最佳方法。

java.time

时间

The java.time framework built into Java 8 and later has a Periodclass to represent a span of time as a number of years, a number of months, and a number of days. But this class is limited to whole days, no representation of hours, minutes, and seconds.

Java 8 及更高版本中内置的 java.time 框架有一个Period类将时间跨度表示为年数、月数和天数。但是这个类仅限于整天,没有小时、分钟和秒的表示。

Note that we specify a time zone, crucial for determining a date. For example, a new day dawns earlier in Paristhan in Montréal.

请注意,我们指定了一个时区,这对于确定日期至关重要。例如,新的一天在巴黎蒙特利尔早。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate now = LocalDate.now( zoneId );
LocalDate then = LocalDate.of( 2001, 1, 1 );
Period period = Period.between( then, now );

Then: 2001-01-01. Now: 2015-09-07. Period: P14Y8M6D. Days: 5362

然后:2001-01-01。现在:2015-09-07。时期:P14Y8M6D。天数:5362

For whole days, then Daylight Saving Time (DST)is irrelevant.

对于一整天,夏令时 (DST)是无关紧要的。

If you want a count of total days, use the ChronoUnitenum which includes some calculation methods. Notice the calculations return a long.

如果您想要计算总天数,请使用ChronoUnit包含一些计算方法的枚举。注意计算返回一个 long。

long days = ChronoUnit.DAYS.between( then, now );  // "5362" seen above.

I have askedabout doing a full period in java.time, including hours, minutes, seconds. Not possible as of Java 8. A surprising workaround using the bundled libraries was suggestedby Meno Hochschild: Use a Durationclass found in the javax.xml.datatype package.

我问过在 java.time 中做一个完整的时期,包括小时、分钟、秒。不可能的,因为Java的8使用捆绑的库令人惊讶的解决办法的建议梅诺尔德:使用一个Duration类中发现的javax.xml.datatype包

Joda-Time

乔达时间

Here is some example code in Joda-Time 2.3.

这是 Joda-Time 2.3 中的一些示例代码。

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime start = new DateTime( 2014, 1, 2, 3, 4, 5, timeZone );
DateTime stop = new DateTime( 2014, 5, 2, 3, 4, 5, timeZone );
Period period = new Period( start, stop );

Calling toStringwill get you a string representation in the form defined by the ISO 8601standard, PnYnMnDTnHnMnS.

调用toString将为您提供ISO 8601标准定义的形式的字符串表示,PnYnMnDTnHnMnS.

回答by John O

With the date4jlibrary:

使用date4j库:

int numDaysBetween = oneDate.numDaysFrom(anotherDate);

回答by Luna Kong

There is simple way to implement it. We can use Calendar.add method with loop. For example as below,

有一个简单的方法来实现它。我们可以在循环中使用 Calendar.add 方法。例如如下,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

The minus days between beginDate and endDate, and the code as below,

beginDate 和 endDate 之间的减天数,代码如下,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The substractation between two days is " + (minusDays + 1));

Have Fun! @.@

玩得开心!@.@

回答by Luna Kong

Java's implementation of dates is poor. If you find Joda-Timetoo complicated, try my little contribution to open source: http://calendardate.sourceforge.net/javadoc/index.html

Java 对日期的实现很差。如果你觉得Joda-Time太复杂,试试我对开源的一点贡献:http: //calendardate.sourceforge.net/javadoc/index.html

回答by Uri

I disagree with the claim that Java doesn't have a mechanism for calculating the difference between dates.

我不同意 Java 没有计算日期之间差异的机制的说法。

Java was designed for global use. It was designed so that there isn't a concept of date, there is only a concept of "time in milliseconds". Any interpretation of such a universal time as the time-and-date in a specific location under a specific convention is merely a projection or a view.

Java 是为全球使用而设计的。它被设计成没有日期的概念,只有“时间以毫秒为单位”的概念。在特定约定下对特定地点的时间和日期等世界时的任何解释都只是一种投影或视图。

The calendar class is used to turn this sort of absolute time into dates. You can also add or subtract date components, if you really need to. The only way to provide a difference in term of components between two times would be Calendar generated and specific. Thus, you could argue that the standard library does not include a smart enough Gregorian Calendar, and I would agree that it leaves some to be desired.

日历类用于将这种绝对时间转换为日期。如果确实需要,您还可以添加或减去日期组件。提供两个时间之间组件差异的唯一方法是生成日历和特定日历。因此,您可能会争辩说标准库不包含足够智能的公历,我同意它还有一些不足之处。

That being said, there are numerous implementations of this kind of functionality, I see others have provided examples.

话虽如此,这种功能有很多实现,我看到其他人提供了示例。