【发布时间】:2020-04-14 08:17:37
【问题描述】:
我正在尝试格式化 Threeten 日期时间,从 yyyy-MM-dd'T'HH:mm:ss 到 yyyy-MM-dd HH:mm:ss。下面是我用来完成任务的代码。
public void testChangeFormat() {
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date1 = LocalDateTime.parse("2020-03-10T15:14:05", inputFormatter);
System.out.println(date1); // prints 2020-03-10T15:14:05
String formattedDate = outputFormatter.format(date1);
System.out.println(formattedDate); // prints 2020-03-10 15:14:05
LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate);
System.out.println(newFormattedDateTime);
}
在我尝试将 formattedDate 解析为 LocalDateTime 之前,一切似乎都按预期工作,LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate);
我什至使用 outputFormatter 将日期时间格式化为 2020-03-10 15:14:05,但是当我尝试将其解析为 LocalDateTime 时,它给了我以下异常:
org.threeten.bp.format.DateTimeParseException: Text '2020-03-10 15:14:05' could not be parsed at index 10
有人可以帮我解决这个问题吗?
【问题讨论】:
-
LocalDateTime是日期/时间值,它没有格式。如果您阅读文档,即toString()的javadoc,您将看到它始终使用T分隔符呈现日期/时间值。如果您想要不同格式的日期/时间值,请使用format(DateTimeFormatter)方法。 -
parse(String)方法相同。它只能解析带有T分隔符的字符串。如果要解析不同格式的文本,请使用parse(String, DateTimeFormatter)方法。