我想提供现代答案。当被问到这个问题时,其他答案都很好,但时间在继续。今天我推荐你使用java.time, the modern Java date and time 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() 与两个ZonedDateTime 对象或两个OffsetDateTimes、两个LocalDateTimes 等一起使用。
如果您需要的不仅仅是秒数,您应该考虑使用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 秒。
为什么选择 java.time?
其他几个答案中使用的Date 类现在早已过时。 Joda-Time 也用于一对夫妇(可能在问题中)现在处于维护模式,没有计划进行重大改进,开发人员正式建议迁移到 java.time,也称为 JSR-310。
问题:我可以在我的 Java 版本中使用现代 API 吗?
如果至少使用 Java 6,则可以。