我在尝试将String
时间戳转换为LocalDateTime
我从数据库接收到这个字符串2018013014364112
,它包含日期和时间,应该2018-01-30 14:36:41.12
以更易读的格式编写。
当我尝试解析它时,LocalDateTime
我得到一个Exception
String timestamp = "2018013014364112"
LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyyMMddHHmmssSS"))
例外:
java.time.format.DateTimeParseException: Text '2018013014364112' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
但是,如果我在String
and中的任何位置放置空间FormatPattern
,那么我会得到预期的结果
String timestamp = "2018 013014364112"
assert LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy MMddHHmmssSS")).toString() == '2018-01-30T14:36:41.120'
此外,当我从模式中删除“ SS
”时,即使没有空格,我也会得到预期的结果String
String timestamp = "20180130143641"
assert LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).toString()
== '2018-01-30T14:36:41'