获取上一次出现的 LocalTime

Get previous occurrence of a LocalTime

如何获取系统时区指定 local time as an instant 的前一次出现?

这基本上意味着在指定时间获取今天或在指定时间获取昨天,具体取决于今天的指定时间是在现在之前还是之后。

当然,因为夏令时,我需要考虑时区切换。也就是说,今天和昨天的时区偏移量可能不同。

这就是我现在得到的:

public Instant getPreviousOccurence(LocalTime scheduledTime) {
    Instant now = Instant.now();
    Instant todayAtSpecifiedTime = now.with(scheduledTime);
    return todayAtSpecifiedTime.isAfter(now) ? todayAtSpecifiedTime.minus(1, ChronoUnit.DAYS) : todayAtSpecifiedTime;
}

但是在查看了 Instant.minus() 的来源后,我注意到它一天减少了 84600 秒,这对我来说是错误的。此外,我不确定 Instant.with() 是否会使用系统时区或 UTC。

编辑 1

如果今天没有出现指定时间(因为时区转换),则应返回时区转换的时刻。如果今天的指定时间出现两次,则应返回过去的最新时间。

编辑 2

和Product Owner核实后发现,如果指定时间在一天内出现两次,总是返回第一个(或者总是返回第二个)就可以了。我们不需要两者。

非常感谢 Jon Skeet 将我指向 ZonedDateTime。这是我使用这种类型的解决方案。

public Instant getPreviousOccurence(LocalTime scheduledTime) {
    Instant now = Instant.now();
    ZonedDateTime todayAtScheduledTime = ZonedDateTime.ofInstant(now, EUROPE_PARIS).with(scheduledTime).withEarlierOffsetAtOverlap();
    if (todayAtScheduledTime.toInstant().isAfter(now)) {
        return todayAtScheduledTime.minusDays(1).withEarlierOffsetAtOverlap().toInstant();
    } else {
        return todayAtScheduledTime.toInstant();
    }
}