我在尝试将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
和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'