1

I'm reading a datetime from database in the format 2017-04-20 11:01:21.053, which I need to parse to the format 04/20/2017 11:01:21

I'm trying to parse this date on a LocalDateTime (Java 8) using the following code:

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

But I get the following error when trying to parse 2017-04-20 11:01:21.053:

Text '2017-04-20 11:01:21.053' could not be parsed at index 14

What am I doing wrong here?

everton
  • 7,579
  • 2
  • 29
  • 42
blu10
  • 534
  • 2
  • 6
  • 28
  • 1
    month ==> MM not mm – assylias Jun 15 '16 at 13:05
  • thank you! changing it give me this error though java.time.format.DateTimeParseException: Text '2017-04-20 07:48:10.807' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=807000, MilliOfSecond=807, SecondOfMinute=10, NanoOfSecond=807000000, MinuteOfHour=48, HourOfAmPm=7},ISO resolved to 2017-04-20 of type java.time.format.Parsed – blu10 Jun 15 '16 at 13:09

1 Answers1

5

Change your DateTimeFormatter to:

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
everton
  • 7,579
  • 2
  • 29
  • 42
  • thanks... as above i now get this error ... java.time.format.DateTimeParseException: Text '2017-04-20 07:48:10.807' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=807000, MilliOfSecond=807, SecondOfMinute=10, NanoOfSecond=807000000, MinuteOfHour=48, HourOfAmPm=7},ISO resolved to 2017-04-20 of type java.time.format.Parsed – blu10 Jun 15 '16 at 13:12
  • You also have to change the hour part – everton Jun 15 '16 at 13:14
  • Hour portion was failing because, since you were using `h`, you had to include somewhere on your date if that was AM/PM, otherwise the parser would have no way to guess that – everton Jun 15 '16 at 13:26
  • thanks for the explanation, was in a rush to get something done and hadnt used this Java 8 feature before... much appreciated – blu10 Jun 15 '16 at 15:11