如何从 Instant 和时间字符串构造 ZonedDateTime?

Posted

技术标签:

【中文标题】如何从 Instant 和时间字符串构造 ZonedDateTime?【英文标题】:How to construct ZonedDateTime from an Instant and a time string? 【发布时间】:2015-10-14 02:54:03 【问题描述】:

给定一个Instant 的对象,一个time string 表示特定ZoneId 的时间,如何构造一个ZonedDateTime 对象,其中包含给定时刻的日期部分(年、月、日) ZoneId 和给定 time string 的时间部分?

例如:

给定一个值为 1437404400000 的 Instant 对象(相当于 20-07-2015 15:00 UTC),一个时间字符串 21:00,以及一个代表 Europe/LondonZoneId 对象,我想构造一个相当于 20-07-2015 21:00 Europe/LondonZonedDateTime 对象强>。

【问题讨论】:

如果有的话,您希望日期如何受时间影响? 我想从瞬间中提取日期部分,从字符串中提取时间部分。时间字符串表示指定时区的时间。 但是瞬间没有日期 - 它只是一个时间点,根据时区的不同,它会在不同的日期。基本上看我的帖子有两个选择... 对,从问题中并不清楚 - 请参阅我的回答以了解两种替代解释及其后果。 Righto - 我已经将我的答案简化为当时的答案。 【参考方案1】:

您需要先将时间字符串解析为LocalTime,然后可以使用区域从Instant 调整ZonedDateTime,然后应用时间。例如:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.US");
LocalTime time = LocalTime.parse(timeText, formatter);
ZonedDateTime zoned = instant.atZone(zoneId)
                             .with(time);

【讨论】:

【参考方案2】:

创建瞬间并确定该瞬间的 UTC 日期:

Instant instant = Instant.ofEpochMilli(1437404400000L);
LocalDate date = instant.atZone(ZoneOffset.UTC).toLocalDate();

// or if you want the date in the time zone at that instant:

ZoneId tz = ZoneId.of("Europe/London");
LocalDate date = instant.atZone(tz).toLocalDate();

解析时间:

LocalTime time = LocalTime.parse("21:00");

根据所需 ZoneId 的 LocalDate 和 LocalTime 创建 ZoneDateTime:

ZonedDateTime zdt = ZonedDateTime.of(date, time, tz);

正如 Jon 所指出的,您需要确定您想要的日期,因为 UTC 中的日期可能与当时给定时区中的日期不同。

【讨论】:

非常感谢您的回答;这很有帮助。

以上是关于如何从 Instant 和时间字符串构造 ZonedDateTime?的主要内容,如果未能解决你的问题,请参考以下文章

Illegal instant due to time zone offset transition (Asia/Shanghai)_夏令时问题

Java 8 – 使用 TimeZone 从 LocalDateTime 创建 Instant [重复]

如何从 Instant 转换为 LocalDate

如何在本地时区将 java.time.Instant 格式化为字符串?

SpringBoot对接收及返回Instant类型的处理(转)

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造`java.time.Instant`的实例(没有创建者,如默认构造