0

I try to parse string do the Date format, but get Unparserable exception:

    public void roundTest() throws ParseException {
        String pattern = "MMM dd, yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String from = "Jul 01, 2021";
        Date result = sdf.parse(from);
    }

The same for java.time package:

    public void roundTest() throws ParseException {
        String from = "Jul 01, 2021";
        String pattern = "MMM dd, yyyy";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        System.out.println(LocalDate.parse(from, formatter));
    }

Error: "java.time.format.DateTimeParseException: Text 'Jul 01, 2021' could not be parsed at index 0"

Where the error?

Valentyn Hruzytskyi
  • 1,772
  • 5
  • 27
  • 59
  • Works fine. https://ideone.com/08boTR – Dave Newton Jul 13 '21 at 15:27
  • 3
    You should **not** use `Date` and `SimpleDateFormat`, as they are obsolete. Use classes from the `java.time` package instead. – MC Emperor Jul 13 '21 at 15:27
  • What is your default locale? Maybe the 3-character month name is different there? – Hulk Jul 13 '21 at 15:28
  • 1
    Here is [an example](https://ideone.com/0kqPKm) using `java.time`. – MC Emperor Jul 13 '21 at 15:32
  • @MCEmperor the same for 'java.time'. Please see updated question – Valentyn Hruzytskyi Jul 13 '21 at 15:50
  • 1
    java.time is helpful enough to tell us where the problem is: index 0, that is, `Jul`. Which confirms that the locale is the problem as mentioned in the linked questions, since July isn’t abbreviated in this way in all locales. – Ole V.V. Jul 13 '21 at 15:56
  • 1
    [Here](https://ideone.com/PNfEiW) is @MCEmperor’s example modified to specify a locale explicitly so that the code also works in non-English locales. – Ole V.V. Jul 13 '21 at 17:19

0 Answers0