YAM*_*YAM 4 java java-8 java-time zoneddatetime
给定一个对象Instant,time string表示特定时间ZoneId,如何构造一个ZonedDateTime具有日期部分(年,月,日)的对象,从给定ZoneId的时刻和给定的时间部分time string?
例如:
给定Instant值1437404400000(相当于20-07-2015 15:00 UTC),时间字符串21:00,以及ZoneId代表Europe/London的对象,我想构造一个ZonedDateTime相当于20-07的对象-2015 21:00欧洲/伦敦.
创建即时消息并确定该瞬间的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();
Run Code Online (Sandbox Code Playgroud)
解析时间:
LocalTime time = LocalTime.parse("21:00");
Run Code Online (Sandbox Code Playgroud)
从所需ZoneId的LocalDate和LocalTime创建ZoneDateTime:
ZonedDateTime zdt = ZonedDateTime.of(date, time, tz);
Run Code Online (Sandbox Code Playgroud)
正如Jon指出的那样,您需要确定您想要的日期,因为UTC中的日期可能与该时刻的给定时区中的日期不同.
你要的时间字符串解析到一个LocalTime第一,那么你可以调整ZonedDateTime从Instant与区域,然后应用时间.例如:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.US");
LocalTime time = LocalTime.parse(timeText, formatter);
ZonedDateTime zoned = instant.atZone(zoneId)
.with(time);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5983 次 |
| 最近记录: |