有很多方法可以实现您想要的。其中一些如下:
- 将给定的
ZonedDateTime 转换为Instant 并从Instant 派生LocalDateTime。
ZonedDateTime zdtUtc = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
Instant instant = zdtUtc.toInstant();
LocalDateTime ldtSwitzerland = LocalDateTime.ofInstant(instant, ZoneId.of("Europe/Zurich"));
ONLINE DEMO
- 使用
ZonedDateTime#withZoneSameInstant将给定的ZonedDateTime转换为所需时区的ZonedDateTime,然后从ZonedDateTime获取LocalDateTime。
ZonedDateTime zdtUtc = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
ZonedDateTime zdtSwitzerland = zdtUtc.withZoneSameInstant(ZoneId.of("Europe/Zurich"));
LocalDateTime ldtSwitzerland = zdtSwitzerland.toLocalDateTime();
ONLINE DEMO
- 将给定的
ZonedDateTime 转换为Instant 可以使用Instant#atZone 转换为ZonedDateTime,然后从ZonedDateTime 中获取LocalDateTime。
ZonedDateTime zdtUtc = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
Instant instant = zdtUtc.toInstant();
ZonedDateTime zdtSwitzerland = instant.atZone(ZoneId.of("Europe/Zurich"));
LocalDateTime ldtSwitzerland = zdtSwitzerland.toLocalDateTime();
ONLINE DEMO
- 使用
DateTimeFormatter 将给定的ZonedDateTime 格式化为与所需时区相关的日期时间字符串,然后通过解析获得的日期时间字符串导出LocalDateTime。 注意:此方法仅用于您的学习目的;您应该在生产代码中实现第一种方式(最顶层)。
ZonedDateTime zdtUtc = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
DateTimeFormatter dtfSwitzerland = DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(ZoneId.of("Europe/Zurich"));
String strZdtSwitzerland = dtfSwitzerland.format(zdtUtc);
LocalDateTime ldt = LocalDateTime
.from(DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(strZdtSwitzerland, new ParsePosition(0)));
ONLINE DEMO
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。