0

The below code throws error, not sure why 1 is not accepted as 01 and throws exception

failure Text '1/1/2020 12:12:12' could not be parsed at index 0
1/1/2020 12:12:12 MM/dd/yyyy HH:mm:ss
try {
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss", Locale.US)
        .withResolverStyle(ResolverStyle.STRICT);
    System.out.println("success " + dateFormatter.parse(1/1/2020 12:12:12));
} catch (Exception e) {
    System.out.println("failure " + e.getMessage());
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 3
    Use M/d/yyyy HH:mm:ss or M/d/uuuu HH:mm:ss – Arvind Kumar Avinash Nov 05 '20 at 13:31
  • 1
    Does this answer your question? [Month without leading zeros in Android](https://stackoverflow.com/questions/8681666/month-without-leading-zeros-in-android) – DPWork Nov 05 '20 at 13:34
  • 1
    @DPWork I think not. That other question is about formatting, not parsing, and is not specifically about the `DateTimeFormatter` asked about here. While it may be somewhat helpful anyway, I have edited in some original question links that I find more appropriate. I agree that this question is a duplicate. – Ole V.V. Nov 06 '20 at 13:47
  • Fair enough - agree that the question isn't quite the same, but all four answers seem like they would answer this question just as well as they answer that question. Your other links are just as good though :) – DPWork Nov 06 '20 at 15:19

1 Answers1

1

DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss", Locale.US) accepts dates with exactly two places in Month and Day. For your input, DateTimeFormatter.ofPattern("M/d/yyyy HH:mm:ss", Locale.US), ResolverStyle.STRICT) is needed.

nkrivenko
  • 1,231
  • 3
  • 14
  • 23