查找下一次出现的时间,例如TemporalAdjuster

DaveyDaveDave:

JSR-310中是否有任何东西可以查找给定时间的下一次出现?我真的在寻找与这个问题相同的东西,只是时间而不是几天。

例如,从世界标准时间2020-09-17的世界标准时间06:30开始,我想查找下一次出现的05:30:

LocalTime time = LocalTime.of(5, 30);
ZonedDateTime startDateTime = ZonedDateTime.of(2020, 9, 17, 6, 30, 0, 0, ZoneId.of("UTC"));

ZonedDateTime nextTime = startDateTime.with(TemporalAdjusters.next(time)); // This doesn't exist

在上面,我想nextTime代表世界标准时间(UTC)05:30(即第二天早上05:30)的2020-09-18。

为了阐明我的期望,所有时间都是05:30:

----------------------------------------
| startDateTime    | expected nextTime |
| 2020-09-07 06:30 | 2020-09-08 05:30  |
| 2020-09-07 05:00 | 2020-09-07 05:30  |
| 2020-09-07 05:30 | 2020-09-08 05:30  |
----------------------------------------
清扫器:

如果您只是想让它与LocalDateTimes和LocalTimes一起使用,或者Temporal每天使用24小时的任何其他类型,则逻辑很简单:

public static TemporalAdjuster nextTime(LocalTime time) {
    return temporal -> {
        LocalTime lt = LocalTime.from(temporal);
        if (lt.isAfter(time)) {
            return temporal.plus(Duration.ofHours(24).minus(Duration.between(time, lt)));
        } else if (lt.isBefore(time)) {
            return temporal.plus(Duration.between(time, lt));
        } else {
            return temporal.plus(Duration.ofHours(24));
        }
    };
}

但是Temporal,对于具有时间成分的所有对象来说这样做实际上非常困难。考虑一下您要做些什么ZonedDateTime当涉及时区时,您如何知道要添加多少时间才能到达下一个5:30?您需要检查区域规则,并确定是否存在过渡。尤其是在例如02:00出现重叠过渡时,这意味着一天中将有例如两个01:30实例。它必须处理您询问“自01:30以后的下一个01:30是什么?”的情况。:)

如果您看一下其他内置的时间调整器,它们都非常简单,因此我想他们只是不想增加这种复杂性。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章