java 计算两个时间戳_Java时间戳计算重叠持续时间与间隔
我相信下面的方法給出了你的Joda時(shí)間解的等價(jià)物。
private static final LocalTime START = LocalTime.of(18, 0);
private static final LocalTime END = LocalTime.of(8, 0);
public static Duration overlap(ZonedDateTime currentStart, ZonedDateTime currentEnd) {
ZonedDateTime singleIntervalStart = currentStart.with(START);
ZonedDateTime singleIntervalEnd = currentStart.plusDays(1).with(END);
if (currentEnd.isBefore(singleIntervalStart)) {
// no overlap
return Duration.ZERO;
}
ZonedDateTime overlapStart = currentStart.isBefore(singleIntervalStart)
? singleIntervalStart : currentStart;
ZonedDateTime overlapEnd = currentEnd.isBefore(singleIntervalEnd)
? currentEnd : singleIntervalEnd;
return Duration.between(overlapStart, overlapEnd);
}
為了使用您問(wèn)題中的時(shí)間戳進(jìn)行嘗試,我使用以下實(shí)用程序方法:
private static void demo(String from, String to) {
ZoneId zone = ZoneId.of("Atlantic/Stanley");
Duration overlapDuration = overlap(LocalDateTime.parse(from).atZone(zone),
LocalDateTime.parse(to).atZone(zone));
System.out.println("" + from + " - " + to + ": " + overlapDuration);
}
現(xiàn)在我這樣稱呼它:
demo("2018-01-02T14:59:18.922", "2018-01-02T14:59:38.804");
demo("2018-01-02T18:32:59.348", "2018-01-02T20:30:41.192");
demo("2018-01-02T01:54:59.363", "2018-01-02T01:54:59.363");
demo("2018-01-03T00:10:38.831", "2018-01-03T00:11:53.103");
輸出為:
2018-01-02T14:59:18.922 - 2018-01-02T14:59:38.804: PT0S
2018-01-02T18:32:59.348 - 2018-01-02T20:30:41.192: PT1H57M41.844S
2018-01-02T01:54:59.363 - 2018-01-02T01:54:59.363: PT0S
2018-01-03T00:10:38.831 - 2018-01-03T00:11:53.103: PT0S
在第一個(gè)示例中,14:59在18:00之前,因此結(jié)果是0的重疊。在第二個(gè)示例中,整個(gè)間隔被計(jì)算為重疊(近2小時(shí))。請(qǐng)注意,在最后兩個(gè)示例中,沒(méi)有報(bào)告重疊,因?yàn)闀r(shí)間在18:00之前很多小時(shí)。我不確定這是否是你想要的,因?yàn)樘┪钍繄?bào)也在08:00之前。
總結(jié)
以上是生活随笔為你收集整理的java 计算两个时间戳_Java时间戳计算重叠持续时间与间隔的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mysql57数据库命令_MySQL 5
- 下一篇: php redis与me m,Redis