ZonedDateTime to LocalDateTime



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

我尝试使用该方法将其解析为ZonedDateTimeparse但失败并出现错误

@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

观察到的结果:

线程"main"中的异常 java.time.format.DateTimeParseException: 无法在索引 0 处解析文本"星期六,13 Jun 2020 23:14:21 GMT">

Java为该特定格式的输入提供了格式化程序。这种格式用于较旧的协议,如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

最新更新