3

I am trying to convert this date to a different format. unfortuantely havnt been successful parsing the date and retaining all the information correctly.

06-Dec-2017 07:14:56.656PM to 2017-12-06 19:14:56.656

If I try to parse the input date

LocalDateTime.parse("06-Dec-2017 07:14:56.656PM",
        DateTimeFormatter.ofPattern("D-MMM-yyyy HH:mm:ss.SSSa"));

I get the following error - not sure what it means?

Exception in thread "main" java.time.format.DateTimeParseException: Text '06-Dec-2017 07:14:56.656PM' could not be parsed: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 12 derived from 2017-01-06
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at com.cordys.coe.alf.logger.DBLogger.main(DBLogger.java:366)
Caused by: java.time.DateTimeException: Conflict found: Field MonthOfYear 1 differs from MonthOfYear 12 derived from 2017-01-06
    at java.time.format.Parsed.crossCheck(Unknown Source)
    at java.time.format.Parsed.crossCheck(Unknown Source)

and if try

System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
        .format((new SimpleDateFormat("DD-MMM-yyyy HH:mm:ss.SSSa")
                .parse("06-Dec-2017 07:14:56.656PM"))));

It give the following which is confusing, and probably not correct. 2017-01-06 07:14:56:656

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 3
    I would suggest that `D` is wrong - From the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) - *"D | day-of-year | number | 189"*, I think you mean `d` – MadProgrammer Dec 07 '17 at 03:58
  • MadProgrammer is right, replace D with d, check this for all conversion symbols: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html – whatamidoingwithmylife Dec 07 '17 at 04:03
  • That message is tricky alrignt. I believe that it means: from day-of-year 6 (capital `D` in the format pattern string) it gets January (month 1), which conflicts with December (month 12). – Ole V.V. Dec 07 '17 at 07:17
  • 1
    Slightly aside, your experience illustrates an important difference between the old and new API quite well: given an incorrect format pattern string for parsing, the modern API will object so you know something is wrong, while `SimpleDateFormat` will usually just give you an incorrect result and pretend all is well, which I consider more dangerous. – Ole V.V. Dec 07 '17 at 07:21

1 Answers1

11

You have 2 problems

  1. D should be d

D represents day of year

d represents day-of-month

  1. HH should be hh

H represents hour-of-day (0-23)

h represents clock-hour-of-am-pm (1-12)

Please change D-MMM-yyyy HH:mm:ss.SSSa to d-MMM-yyyy hh:mm:ss.SSSa

For more information , check the oracle docs

Community
  • 1
  • 1
SpringLearner
  • 13,738
  • 20
  • 78
  • 116