1

我有以下代码。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
LocalDateTime myDate =  LocalDateTime.parse("2020-11-16T02:27:39.345Z", formatter);

但它在第二行抛出错误。不知道为什么抱怨Z

java.time.format.DateTimeParseException: Text '2020-11-16T02:27:39.345Z' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
4

1 回答 1

3

LocalDateTime没有时区或区域偏移信息,而您的日期时间字符串具有区域偏移。日期时间字符串末尾的字母Z代表祖鲁语,即UTC. 您可以将其解析为OffsetDateTimeorZonedDateTimeInstant直接(即不使用 custom DateTimeFormatter)。

演示:

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        String dateTimeString = "2020-11-16T02:27:39.345Z";
        OffsetDateTime odt = OffsetDateTime.parse(dateTimeString);
        System.out.println(odt);
        ZonedDateTime zdt = ZonedDateTime.parse(dateTimeString);
        System.out.println(zdt);
        Instant instant = Instant.parse(dateTimeString);
        System.out.println(instant);
    }
}

输出:

2020-11-16T02:27:39.345Z
2020-11-16T02:27:39.345Z
2020-11-16T02:27:39.345Z
于 2020-11-18T20:48:37.920 回答