在 Java 中,如何获得两个日期之间的秒差?

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

In Java, how do I get the difference in seconds between 2 dates?

javadatetimedate

提问by snakile

The Java class library has a class named DateTime. DateTime has this method:

Java 类库有一个名为 DateTime 的类。DateTime 有这个方法:

int daysBetween(DateTime other)

which returns the number of days between this and the parameter. It doesn't have a method

它返回此参数与参数之间的天数。它没有方法

int secondsBetween(DateTime other)

which I happen to need. Is there a class which is similar to DateTime but has such a method?

我碰巧需要。是否有一个类似于 DateTime 但有这样一个方法的类?

采纳答案by Scott Stanchfield

Not familiar with DateTime...

不熟悉日期时间...

If you have two Dates you can call getTime on them to get millseconds, get the diff and divide by 1000. For example

如果您有两个日期,您可以对它们调用 getTime 以获得毫秒,获取差异并除以 1000。例如

Date d1 = ...;
Date d2 = ...;
long seconds = (d2.getTime()-d1.getTime())/1000;

If you have Calendar objects you can call

如果您有 Calendar 对象,您可以调用

c.getTimeInMillis()

and do the same

并做同样的事情

回答by Brian Agnew

Which class ? Do you mean the Joda DateTimeclass ? If so, you can simply call getMillis()on each, and perform the appropriate subtraction/scaling.

哪一堂课 ?你的意思是 Joda DateTime类?如果是这样,您可以简单地调用getMillis()每个,并执行适当的减法/缩放。

I would recommend Joda for date/time work, btw, due to it's useful and intuitive API, and its thread-safety for formatting/parsing options.

我会推荐 Joda 进行日期/时间工作,顺便说一句,因为它有用且直观的 API,以及它用于格式化/解析选项的线程安全性。

回答by andri

There is no such class as DateTimein the standard Java SE API. Although there is one in joda-time, even that does not have a daysBetweenmethod.

没有DateTime标准 Java SE API 中的类。乔达时代虽然有,但也没有daysBetween办法。

Using the standard Java API, the easiest way to get seconds between two java.util.Dateobjects would be to subtract their timestamps and divide by 1000:

使用标准 Java API,获取两个java.util.Date对象之间的秒数的最简单方法是减去它们的时间戳并除以 1000:

int secondsBetween = (date1.getTime() - date2.getTime()) / 1000;

回答by Johannes Weiss

That should do it:

那应该这样做:

Date a = ...;
Date b = ...;

Math.abs(a.getTime()-b.getTime())/1000;

Here the relevant documentation: Date.getTime(). Be aware that this will only work for dates after January 1, 1970, 00:00:00 GMT

这里的相关文档:Date.getTime()。请注意,这仅适用于格林威治标准时间 1970 年 1 月 1 日 00:00:00 之后的日期

回答by Pool

It is not recommended to use java.util.Dateor System.currentTimeMillis()to measure elapsed times. These dates are not guaranteed to be monotonic and will changes occur when the system clock is modified (eg when corrected from server). In probability this will happen rarely, but why not code a better solution rather than worrying about possibly negative or very large changes?

不建议使用java.util.DateSystem.currentTimeMillis()测量经过的时间。这些日期不能保证是单调的,并且会在系统时钟被修改时发生变化(例如,当从服务器更正时)。可能这种情况很少发生,但为什么不编写一个更好的解决方案,而不是担心可能出现负面或非常大的变化呢?

Instead I would recommend using System.nanoTime().

相反,我建议使用System.nanoTime().

long t1 = System.nanoTime();
long t2 = System.nanoTime();

long elapsedTimeInSeconds = (t2 - t1) / 1000000000;

EDIT

编辑

For more information about monoticity see the answerto a related question I asked, where possible nanoTime uses a monotonic clock. I have tested but only using Windows XP, Java 1.6 and modifying the clock whereby nanoTimewas monotonic and currentTimeMilliswasn't.

有关单调性的更多信息,请参阅我提出的相关问题的答案,nanoTime 在可能的情况下使用单调时钟。我已经测试过,但只使用 Windows XP、Java 1.6 并修改了nanoTime单调的时钟,currentTimeMillis而不是单调的。

Also from Java's Real time doc's:

同样来自Java 的实时文档

Q: 50. Is the time returned via the real-time clock of better resolution than that returned by System.nanoTime()?

The real-time clock and System.nanoTime() are both based on the same system call and thus the same clock.

With Java RTS, all time-based APIs (for example, Timers, Periodic Threads, Deadline Monitoring, and so forth) are based on the high-resolution timer. And, together with real-time priorities, they can ensure that the appropriate code will be executed at the right time for real-time constraints. In contrast, ordinary Java SE APIs offer just a few methods capable of handling high-resolution times, with no guarantee of execution at a given time. Using System.nanoTime() between various points in the code to perform elapsed time measurements should always be accurate.

Q: 50. 实时时钟返回的时间是否比 System.nanoTime() 返回的时间分辨率更高?

实时时钟和 System.nanoTime() 都基于相同的系统调用,因此也是相同的时钟。

使用 Java RTS,所有基于时间的 API(例如,计时器、周期线程、截止日期监控等)都基于高分辨率计时器。而且,连同实时优先级,它们可以确保在正确的时间执行适当的代码以实现实时约束。相比之下,普通的 Java SE API 只提供了几种能够处理高分辨率时间的方法,并不能保证在给定时间执行。在代码中的各个点之间使用 System.nanoTime() 来执行经过的时间测量应该总是准确的。

回答by Fabio Kenji

Just a pointer: If you're calculating the difference between two java.util.Date the approach of subtracting both dates and dividing it by 1000 is reasonable, but take special care if you get your java.util.Date reference from a Calendar object. If you do so, you need to take account of daylight savings of your TimeZone since one of the dates you're using might take place on a DST period.

只是一个指针:如果您正在计算两个 java.util.Date 之间的差异,则将两个日期相减并除以 1000 的方法是合理的,但如果您从 Calendar 对象中获取 java.util.Date 引用,请特别小心. 如果这样做,您需要考虑时区的夏令时,因为您使用的日期之一可能发生在 DST 期间。

That is explained on Prasoon's link, I recommend taking some time to read it.

这在 Prasoon 的链接上有解释,我建议花一些时间阅读它。

回答by cserepj

If you're using Joda (which may be coming as jsr 310 in JDK 7, separate open source api until then) then there is a Seconds class with a secondsBetween method.

如果您使用的是 Joda(它可能在 JDK 7 中作为 jsr 310 出现,在此之前将开源 api 分开)那么有一个 Seconds 类和一个 secondsBetween 方法。

Here's the javadoc link: http://joda-time.sourceforge.net/api-release/org/joda/time/Seconds.html#secondsBetween(org.joda.time.ReadableInstant,%20org.joda.time.ReadableInstant)

这是 javadoc 链接:http: //joda-time.sourceforge.net/api-release/org/joda/time/Seconds.html#secondsBetween(org.joda.time.ReadableInstant,%20org.joda.time.ReadableInstant)

回答by Pascal-Louis Perez

You should do

你应该做

org.joda.time.Seconds.secondBetween(date1, date2)

回答by shem

You can use org.apache.commons.lang.time.DateUtilsto make it cleaner:

您可以使用org.apache.commons.lang.time.DateUtils使其更清洁:

(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND

回答by Mauro Midolo

Use this method:

使用这个方法:

private Long secondsBetween(Date first, Date second){
    return (second.getTime() - first.getTime())/1000;
}