Search code examples
javajava-timelocaldatetimedatetimeformatter

Date Format Issue With DateTimeFormatter


I have a date in the following format: 1/1/2020 3:4:7 AM I am trying to format it using DateTimeFormatter.

I have the following code with a formatter to parse it, but it doesn't work.

LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM", DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"));

I get the following exception:

java.time.format.DateTimeParseException: Text '1/1/2020 3:4:7 AM' could not be parsed at index 0

Can anyone help me?


Solution

  • Two separate problems:

    Wrong counts

    You're using e.g. MM which is an explicit: Always the full amount of digits, zero-padded. Your string is not like that, it's just the number. So, make that M/d/uuuu h:m:s a.

    EDIT: Changed yyyy to uuuu, thanks, @deHaar. Reasoning: yyyy or uuuu rarely matters, but note that this mean 4 digits are required. The difference kicks in for years before 0: uuuu goes negative, yyyy does not and expects you to use e.g. GG so that you get 44 BC instead of -44. In that way, uuuu is just more correct, even though usually the difference is not going to come up.

    Missing locale

    The second problem is that you should pretty much never use this version of ofPattern - it has a bug, which you can't catch with unit tests, which makes that a bug that is thousands of times 'heavier', and thus, a real problem.

    You need to specify locale. Without it, 'AM' is not going to parse unless your platform default locale is english.

    Putting it together

    LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM",
      DateTimeFormatter.ofPattern("M/d/uuuu h:m:s a", Locale.ENGLISH));
    

    works great.