java 计算两个时间戳_Java时间戳计算重叠持续时间与间隔

我相信下面的方法给出了你的Joda时间解的等价物。

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);

}

为了使用您问题中的时间戳进行尝试,我使用以下实用程序方法:

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);

}

现在我这样称呼它:

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

在第一个示例中,14:59在18:00之前,因此结果是0的重叠。在第二个示例中,整个间隔被计算为重叠(近2小时)。请注意,在最后两个示例中,没有报告重叠,因为时间在18:00之前很多小时。我不确定这是否是你想要的,因为泰晤士报也在08:00之前。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值