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

sna*_*ile 64 java datetime date

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

int daysBetween(DateTime other)
Run Code Online (Sandbox Code Playgroud)

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

int secondsBetween(DateTime other)
Run Code Online (Sandbox Code Playgroud)

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

Sco*_*eld 155

不熟悉DateTime ......

如果你有两个日期,你可以在它们上面调用getTime来获得毫秒,得到差异并除以1000.例如

Date d1 = ...;
Date d2 = ...;
long seconds = (d2.getTime()-d1.getTime())/1000;
Run Code Online (Sandbox Code Playgroud)

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

c.getTimeInMillis()
Run Code Online (Sandbox Code Playgroud)

并做同样的事情

  • 当时差不那么高时 - int seconds =(int)((d2.getTime() - d1.getTime())/ 1000); (2认同)

小智 8

你应该做

org.joda.time.Seconds.secondBetween(date1, date2)
Run Code Online (Sandbox Code Playgroud)

  • @divonas没有任何区别.他的符号明确提到了乔达 (4认同)
  • 欢迎来到StackOverflow,感谢您的贡献.如果你解释为什么这是要走的路,这将是一个更强的帖子. (2认同)

Joh*_*iss 7

应该这样做:

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

Math.abs(a.getTime()-b.getTime())/1000;
Run Code Online (Sandbox Code Playgroud)

这里有相关文档:Date.getTime().请注意,这仅适用于1970年1月1日00:00:00 GMT之后的日期


she*_*hem 6

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

(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND
Run Code Online (Sandbox Code Playgroud)


Ole*_*.V. 6

我想提供现代答案。当问这个问题时,其他答案都很好,但是时间还在继续。今天,我建议您使用java.time现代的Java日期和时间API

    ZonedDateTime aDateTime = ZonedDateTime.of(2017, 12, 8, 19, 25, 48, 991000000, ZoneId.of("Europe/Sarajevo"));
    ZonedDateTime otherDateTime = ZonedDateTime.of(2017, 12, 8, 20, 10, 38, 238000000, ZoneId.of("Europe/Sarajevo"));

    long diff = ChronoUnit.SECONDS.between(aDateTime, otherDateTime);
    System.out.println("Difference: " + diff + " seconds");
Run Code Online (Sandbox Code Playgroud)

打印:

Difference: 2689 seconds
Run Code Online (Sandbox Code Playgroud)

ChronoUnit.SECONDS.between()适用于两个ZonedDateTime对象或两个OffsetDateTime,两个LocalDateTime,等等。

如果您只需要几秒钟,那么您应该考虑使用Duration该类:

    Duration dur = Duration.between(aDateTime, otherDateTime);
    System.out.println("Duration: " + dur);
    System.out.println("Difference: " + dur.getSeconds() + " seconds");
Run Code Online (Sandbox Code Playgroud)

打印:

Duration: PT44M49.247S
Difference: 2689 seconds
Run Code Online (Sandbox Code Playgroud)

两行中的前一行以ISO 8601格式打印持续时间,输出表示持续时间为44分钟49.247秒。

为什么选择java.time?

Date在其他几个答案中使用的类现在已经过时了。Joda-Time在几个(可能还有一个问题)中也使用过,现在处于维护模式,没有计划进行重大增强,开发人员正式建议迁移到java.time,也称为JSR-310。

问:我可以在Java版本中使用现代API吗?

如果至少使用Java 6,则可以。

  • 非常被低估的答案。Jodatime 这里的计算有点乱。然而 `ChronoUnit.SECONDS. Between(oldDate.toInstant(), newDate.toInstant())` 相当容易记住。 (3认同)

and*_*dri 5

DateTime标准Java SE API中没有这样的类.虽然在joda-time中有一个,但即便没有daysBetween方法.

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

int secondsBetween = (date1.getTime() - date2.getTime()) / 1000;
Run Code Online (Sandbox Code Playgroud)


Poo*_*ool 5

It is not recommended to use java.util.Date or 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?

Instead I would recommend using System.nanoTime().

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

long elapsedTimeInSeconds = (t2 - t1) / 1000000000;
Run Code Online (Sandbox Code Playgroud)

EDIT

For more information about monoticity see the answer to 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 nanoTime was monotonic and currentTimeMillis wasn't.

Also from Java's Real time doc's:

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.