ZonedDateTime 到 LocalDateTime

ZonedDateTime to LocalDateTime

我有一个表示带区域的日期时间的字符串,我想将字符串表达式转换为 LocalDateTime

我尝试使用 parse 方法将其解析为 ZonedDateTime,但因错误而失败

 @SerializedName("Expires")
 private String expires = "Sat, 13 Jun 2020 23:14:21 GMT";

 public LocalDateTime getExpiredDateTime() {
     return ZonedDateTime.parse(expires).toLocalDateTime();
 }

预期结果:LocalDateTime2020-06-13T23:14:21

观测结果:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sat, 13 Jun 2020 23:14:21 GMT' could not be parsed at index 0

Java provides a formatter for that particular format of input. That format was used in older protocols such as RFC 1123(现在在现代协议中被 ISO 8601 取代)。

ZonedDateTime
.parse(
    "Sat, 13 Jun 2020 23:14:21 GMT" ,
    DateTimeFormatter. RFC_1123_DATE_TIME
)
.toLocalDateTime()

该输入的旧版格式设计不当。我建议就 ISO 8601.

教育该数据的发布者
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "Sat, 13 Jun 2020 23:14:21 GMT";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss z");
        ZonedDateTime zdt = ZonedDateTime.parse(dateTimeStr, formatter);
        System.out.println(zdt);

        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);
    }
}

输出:

2020-06-13T23:14:21Z[GMT]
2020-06-13T23:14:21

[更新]

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateTimeStr = "Sat, 13 Jun 2020 23:14:21 GMT";

        DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;

        ZonedDateTime zdt = ZonedDateTime.parse(dateTimeStr, formatter);
        System.out.println(zdt);

        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);
    }
}

输出:

2020-06-13T23:14:21Z
2020-06-13T23:14:21