【问题标题】:How to use java.time.ZonedDateTime & format.DateTimeFormatter without GMT?如何在没有 GMT 的情况下使用 java.time.ZonedDateTime 和 format.DateTimeFormatter?
【发布时间】:2021-10-27 14:21:37
【问题描述】:

执行以下操作:

val zonedFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z")

ZonedDateTime.from(zonedFormatter.parse("31.07.2020 14:15 GMT"))

给我:

"displayDate": "2020-07-31T14:15:00Z[GMT]"

我想要没有 [GMT]:

"displayDate": "2020-07-31T14:15:00Z"

【问题讨论】:

  • 给我什么“给你”?这是 JSON 吗?您是否在某处序列化包含ZonedDateTime 的实例?怎么样?

标签: java java-time


【解决方案1】:

您可以使用DateTimeFormatter.ISO_OFFSET_DATE_TIME 来格式化解析后的ZonedDateTime。但是,如果您希望日期时间始终采用 UTC,我建议您将解析后的 ZonedDateTime 转换为 Instant

演示:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm z", Locale.ENGLISH);

        ZonedDateTime zdt = ZonedDateTime.from(dtfInput.parse("31.07.2020 14:15 GMT"));
        System.out.println(zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

        System.out.println(zdt.toInstant());
    }
}

输出:

2020-07-31T14:15:00Z
2020-07-31T14:15:00Z

ONLINE DEMO

通过 Trail: Date Time 了解有关 modern Date-Time API* 的更多信息。查看this answerthis answer 了解如何将java.time API 与JDBC 结合使用。


* 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring。请注意,Android 8.0 Oreo 已经提供了support for java.time

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2010-09-11
    • 2019-11-15
    • 2013-06-30
    • 2015-08-09
    • 2018-08-21
    • 2017-06-11
    相关资源
    最近更新 更多