在Java中,我如何获得2个日期之间的秒数差异?
Java 类库有一个名为 DateTime 的类。日期时间有这个方法:
int daysBetween(DateTime other)
它返回此参数与参数之间的天数。它没有方法
int secondsBetween(DateTime other)
我碰巧需要。有没有一个类类似于DateTime但有这样的方法?
Java 类库有一个名为 DateTime 的类。日期时间有这个方法:
int daysBetween(DateTime other)
它返回此参数与参数之间的天数。它没有方法
int secondsBetween(DateTime other)
我碰巧需要。有没有一个类类似于DateTime但有这样的方法?
不熟悉日期时间...
如果你有两个日期,你可以调用 getTime 来获取毫秒,获取差异并除以 1000。例如
Date d1 = ...;
Date d2 = ...;
long seconds = (d2.getTime()-d1.getTime())/1000;
如果您有日历对象,您可以调用
c.getTimeInMillis()
并做同样的事情
我想提供现代的答案。当这个问题被问到时,其他答案都很好,但时间在流逝。今天,我建议您使用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");
这打印:
Difference: 2689 seconds
ChronoUnit.SECONDS.between()
适用于两个对象或两个 s、两个 s 等。ZonedDateTime
OffsetDateTime
LocalDateTime
如果你需要的不仅仅是秒,你应该考虑使用这个类:Duration
Duration dur = Duration.between(aDateTime, otherDateTime);
System.out.println("Duration: " + dur);
System.out.println("Difference: " + dur.getSeconds() + " seconds");
这打印:
Duration: PT44M49.247S
Difference: 2689 seconds
两行中的前者以ISO 8601格式打印持续时间,输出表示持续时间为44分钟和49.247秒。
其他几个答案中使用的类现在早已过时。Joda-Time也用于一对夫妇(可能在问题中)现在处于维护模式,没有计划进行重大增强,开发人员正式建议迁移到,也称为JSR-310。Date
java.time
如果至少使用Java 6,则可以。