Java 如何从瞬间和时间字符串构造ZoneDateTime?

Java 如何从瞬间和时间字符串构造ZoneDateTime?,java,java-8,java-time,zoneddatetime,Java,Java 8,Java Time,Zoneddatetime,给定一个即时对象,一个时间字符串表示特定区域ID的时间,如何构造一个区域DateTime对象,其中日期部分(年、月、日)从给定的区域ID的即时开始,时间部分从给定的时间字符串开始 例如: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.US"); LocalTime time = LocalTime.parse(timeText, formatter); ZonedDateTime zoned =

给定一个
即时
对象,一个
时间字符串
表示特定
区域ID
的时间,如何构造一个
区域DateTime
对象,其中日期部分(年、月、日)从给定的
区域ID
的即时开始,时间部分从给定的
时间字符串
开始

例如:

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

给定一个即时值对象143740400000(相当于20-07-2015 15:00 UTC),一个时间字符串21:00,以及一个代表欧洲/伦敦的
ZoneId
对象,我想构造一个
ZonedDateTime
对象,相当于20-07-2015 21:00 Europe/London

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

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

创建瞬间并确定该瞬间的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中的日期可能与当时给定时区中的日期不同。

如果有,您希望日期如何受时间的影响?我想从即时中提取日期部分,从字符串中提取时间部分。时间字符串表示指定时区的时间。但是一个瞬间没有日期-它只是一个时间点,根据时区的不同,时间点在不同的日期。请参阅我的帖子,了解两种选择,基本上……对,这在问题中并不清楚——请参阅我的答案,了解两种不同的解释,以及它们的后果。对,我已经将我的答案简化为一种。非常感谢你的回答;这很有帮助。