【发布时间】:2020-01-30 15:08:27
【问题描述】:
我需要将 String 中的以下日期格式解析为 Java LocalDateTime。
所以我得到这样的字符串日期:2019-09-20T12:36:39.359
我有以下单元测试:
@Test
public void testDateTime() {
assertEquals(SomeObject.getLocalDate(), LocalDateTime.parse(“2019-09-20T12:36:39.359”, DateTimeFormatter.ofPattern("yyyy-MM-ddThh:mm:ss.SSS")));
}
单元测试失败并出现异常:
java.lang.IllegalArgumentException: Unknown pattern letter: T
at java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1661)
at java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1570)
at java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:536)
如何正确地将这种格式的日期解析为LocalDateTime?
【问题讨论】:
-
你可以用单引号转义 T:"yyyy-MM-dd'T'hh:mm:ss.SSS"
-
您的字符串是ISO 8601 格式,默认为
LocalDateTime,因此您可以省略格式化程序:LocalDateTime.parse("2019-09-20T12:36:39.359")。不过,解析后的LocalDateTime对象永远不会等于String。