字符串到LocalDateTime引发DateTimeParseException

时间:2018-01-30 13:17:07

标签: java java-time datetime-parsing java.time.instant

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

但是,如果我在StringFormatPattern的任何位置放置空格,那么我会得到预期的结果

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'

0 个答案:

没有答案