【发布时间】:2023-03-27 01:34:02
【问题描述】:
我想从特定时区的 Java(也是 UTC)获取 UTC 瞬间(因为我的数据库存储在 UTC 中),这是我迄今为止尝试过的:
public static Instant getStartOfTheDayDateTime(Instant instant, String zoneId) {
ZonedDateTime zoned = instant.atZone(ZONE_ID_TO_ZONE_MAP.get(zoneId));
ZoneId zone = ZoneId.of(zoneId);
return zoned.toLocalDate().atStartOfDay(zone).toInstant();
// ZonedDateTime startOfTheDay = zoned.withHour(0)
// .withMinute(0)
// .withSecond(0)
// .withNano(0);
//
// return startOfTheDay.toInstant();
}
public static Instant getEndOfTheDayDateTime(Instant instant, String zoneId) {
ZonedDateTime zoned = instant.atZone(ZONE_ID_TO_ZONE_MAP.get(zoneId));
ZonedDateTime endOfTheDay = zoned.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0)
.plusDays(1);
return endOfTheDay.toInstant();
}
每次尝试都会显示:
2020-04-10 22:00:00.0(Timestamp), 2020-04-11 22:00:00.0(Timestamp)
- 这是欧洲/巴黎地区 UTC 时间的开始/结束时间吗?
- 我期待有
2020-04-11 02:00:00.0(Timestamp), 2020-04-12 02:00:00.0(Timestamp)
【问题讨论】:
-
我在你的代码中没有看到任何老式的
Timestamp,所以一定有一些东西你没有向我们展示?但是,是的,鉴于时间戳以 UTC 打印,它们表示巴黎一天的开始和结束。 -
这能回答你的问题吗? Java Date Time conversion to given timezone
-
将一天中的小时设置为 0 对于获取一天的开始并不总是正确的。在某些情况下,夏令时 (DST) 在某个时区的午夜开始,因此一天的第一刻是 01:00。您使用
atStartOfDay()是正确且防弹的方式。
标签: java spring date datetime localization