【发布时间】:2022-01-12 09:44:32
【问题描述】:
我正在尝试在 java.time 中解析这些日期,然后获取 String 表示。
2021-12-27T09:15:09.738+02:00
2022-01-11T20:04:21+02:00
我读到了类似的answer,并创建了一个方法来解析上述日期并返回具有所需格式的String:
public String getDatetimeFromDatetimeWithT(String dateFull) {
String date = "";
try {
LocalDateTime ldate = LocalDateTime.parse(dateFull, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
date = ldate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (Exception e) {
System.out.println(dateFull + " not matched 1 " + e);
}
try {
LocalDateTime ldate = LocalDateTime.parse(dateFull, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
date = ldate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (Exception e) {
System.out.println(dateFull + " not matched 2" + e);
}
return date;
}
但是,没有匹配的模式。我在这里缺少什么?
更新:在这两个日期我都得到了 + 字符的异常。
2021-12-27T09:15:09.738+02:00 not matched 1 java.time.format.DateTimeParseException: Text '2021-12-27T09:15:09.738+02:00' could not be parsed at index 23
2022-01-11T20:04:21+02:00 not matched 2 java.time.format.DateTimeParseException: Text '2022-01-11T20:04:21+02:00' could not be parsed at index 19
【问题讨论】:
-
您正在使用可能假定 ZonedDateTime 的 OffsetDateTime 表示。使用 ZonedDateTime。