LocalDateTime解析错误(Java 8)

时间:2016-06-15 12:59:41

标签: java datetime java-8

我正在以2017-04-20 11:01:21.053格式从数据库中读取日期时间,我需要将其解析为格式04/20/2017 11:01:21

我尝试使用以下代码在LocalDateTime(Java 8)上解析此日期:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss.SSS");
LocalDateTime date = LocalDateTime.parse(dateToFormat, formatter);

但是在尝试解析2017-04-20 11:01:21.053时出现以下错误:

  

文字' 2017-04-20 11:01:21.053'无法在索引14处解析

我在这里做错了什么?

1 个答案:

答案 0 :(得分:5)

将DateTimeFormatter更改为:

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")

Formats

   Symbol  Meaning                     Presentation      Examples
   ------  -------                     ------------      -------
   y       year-of-era                 year              2004; 04
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10
   h       clock-hour-of-am-pm (1-12)  number            12
   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978