java - 如何格式化 ZonedDateTime

标签 java zoneddatetime java-time

我正在尝试获取存储为 UTC 的日期时间并将其转换为给定时区的日期时间。据我所知,ZonedDateTime 是正确的(“美国/芝加哥”比 UTC 晚 5 小时),但 DateTimeFormatter 在格式化日期时间时没有考虑偏移量。

我的挂钟时间:中午 12:03

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a")
LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("America/Chicago"));

log.info("Now: " + now);
log.info("Zoned date time: " + zonedDateTime);
log.info("Formatted date time: " + zonedDateTime.format(formatter));

输出:

Now: 2019-08-29T17:03:10.041
Zoned date time: 2019-08-29T17:03:10.041-05:00[America/Chicago]
Formatted date time: 08/29/2019 05:03 PM

我期望的格式化时间:08/29/2019 12:03 PM

最佳答案

LocalDateTime 是没有时区的日期/时间。因此,您所做的就是获取 UTC 日期时间,然后使用 .atZone 告诉 Java 该日期/时间实际上是美国/芝加哥时间,而不是转换它位于正确的时区。

你应该做的是这样的:

ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime zonedDateTime = now.withZoneSameInstant(ZoneId.of("America/Chicago"));

log.info("Now: " + now);
log.info("Zoned date time: " + zonedDateTime);
log.info("Formatted date time: " + zonedDateTime.format(formatter));

关于java - 如何格式化 ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57715053/

相关文章:

java - 如何在 Java 中查看本地化 `FormatStyle` 的 `DateTimeFormatter` 的每个排列?

java - 从一个 Selenium session 到另一个 Selenium session 长期保存 Cookie 的最佳方法?

java - XMPP 服务连接终止

java - 将 mysql 日期解析为 ZonedDateTime

Java时间解析 "Jun 26th 2021, 04:30:15 pm NY"

Java Gregorian Calendar.to ZonedDateTime() 返回过去日期的不同日期

java - 获取 java.lang.ClassCastException : java. lang.Integer 无法转换为 [Ljava.lang.Object 错误

java - 如何使用 JDBC/Spring 调用 Oracle 存储过程,其中某些参数类型是用户定义的?

Android IN Java 8 java.time

java-8 - Set<LocalDate> 包含 LocalDate 最佳实践