确定一个 Instant 是否是另一个 Instant 之后的一天,考虑时区

Determine if one Instant is the day after another Instant, factoring in timezone

时间戳将存储在数据库中。确定一个时间戳 "b" 是否在另一个时间戳 "a" 之后的第二天的解决方案是什么?

时区将作为参数提供。

例如,考虑:

Instant a = Instant.ofEpochSecond(1511928000L); // 11/29/17 4 AM
Instant b = Instant.ofEpochSecond(1511935200L); // 11/29/17 6 AM

如果用户想知道b是否是东部时区a的后一天(-5小时),程序会比较:

17 年 11 月 28 日晚上 11 点的时刻 a 和 2017 年 11 月 29 日凌晨 1 点的时刻 b,并确定 b 是 a 的后一天。

可以使用 ZoneId.getAvailableZoneIds() 获取正确的区域 ID。 这对于特定国家/地区的日间节省很有用。

除了 ZonedDateTime 也可以是:

ZoneId zoneId = ZoneId.of("UTC-5h");
OffsetDateTime ad = OffsetDateTime.ofInstant(a, zoneId);
OffsetDateTime bd = OffsetDateTime.ofInstant(b, zoneId);
return ad.getDayOfYear() != bd.getDayOfYear();

评论后更好的解决方案 - 对于不同年份的同一天:

ZoneId zoneId = ZoneId.of("UTC-5h");
ZonedDateTime ad = ZonedDateTime.ofInstant(a, zoneId).truncatedTo(ChronoUnit.DAYS);
ZonedDateTime bd = ZonedDateTime.ofInstant(b, zoneId).truncatedTo(ChronoUnit.DAYS);
return !ad.equals(bd);

找到解决方案:

public static void main(String[] args) {
    Instant a = Instant.ofEpochSecond(1511928000L); // 11/29/17 4 AM
    Instant b = Instant.ofEpochSecond(1511935200L); // 11/29/17 6 AM
    ZoneId localZone = ZoneId.of("America/New_York"); // Can be any zone ID

    if (isBOneDayAfterA(a, b, localZone)) {
        System.out.println("b is one day after a!");
    } else {
        System.out.println("b is NOT one day after a");
    }
}

public static boolean isBOneDayAfterA(Instant a, Instant b, ZoneId localZone) {
    LocalDateTime aAdjusted = LocalDateTime.ofInstant(a, localZone);
    LocalDateTime bAdjusted = LocalDateTime.ofInstant(b, localZone);
    LocalDate aDate = aAdjusted.toLocalDate();
    LocalDate bDate = bAdjusted.toLocalDate();

    return bDate.minusDays(1).equals(aDate);
}