具有时区和毫秒的 LocalDateTime 格式

LocalDateTime format with time zone and milliseconds

我正在尝试编写一个 DateTimeFormatter 来解析以下格式:

2020-05-29T07:51:33.106-07:00

我看过ISO_OFFSET_DATE_TIME,但问题是它不包含毫秒。所以我决定自己写。

没有时区也很容易做到:

public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106", formatter)
    );
}

It works just fine

但是当我尝试添加格式为

的时区时
public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106-07:00", formatter)
    );
}

It now fails with an exception 时区无法解析。

Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-05-29T07:51:33.106-07:00' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Ideone.main(Main.java:16)

如何解析这种格式的时区?

来自 Javadoc(强调我的):

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. The output will be '+0000' when the offset is zero. Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero. Five letters outputs the hour, minute, with optional second if non-zero, with colon. It outputs 'Z' if the offset is zero. Six or more letters throws IllegalArgumentException.

将单个 Z 更改为 ZZZZZ

tl;博士

无需定义格式化程序。

OffsetDateTime.parse( "2020-05-29T07:51:33.106-07:00" )

详情

是正确的。另外,你用错了class.

LocalDateTime class 只代表一个带有时间的日期,仅此而已。 class 故意缺少任何时区或与 UTC 的偏移量的概念。因此,这个 class 不能代表一个时刻,不是时间轴上的一个点。

所以,解析带有偏移量的字符串,最后的 -07:00 作为 LocalDateTime 没有意义。 offset这些有价值的信息将被忽略、丢弃

相反,解析为 OffsetDateTime

奖励:您的整个格式化程序问题都没有实际意义。您输入的字符串符合 OffsetDateTime class when parsing/generating 字符串中默认使用的标准 ISO 8601 格式。您根本不需要定义任何自定义格式模式。

OffsetDateTime.parse( "2020-05-29T07:51:33.106-07:00" )

…和:

myOffsetDateTime.toString() 

你说:

But when I tried to add a timezone

不,您使用字符串 -07:00 添加了与 UTC 的偏移量,而不是时区。

  • 偏移只是本初子午线之前或之后的小时-分钟-秒数。
  • 时区更多。时区有一个名称,例如 America/Edmonton。一个时区有过去、现在、 以及未来对所使用的挂钟时间偏移量的更改 特定地区的人。