0

I am facing DateTimeParseException even after giving appropriate format

DateTimeFormatter ft = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy");
LocalDateTime.parse("Tue Jan 08 00:00:00 IST 2019", ft);

Please help if I am missing anything?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • 4
    Might be a matter of locale. Is Tuesday called Tuesday in the language your computer is set with? – kumesana Jan 08 '19 at 16:05
  • It seems you are trying to parse the return value from `Date.toString()`? If so it’s better to convert more directly, for example `LocalDateTime.ofInstant(yourDate.toInstant(), ZoneId.systemDefault())`. – Ole V.V. Jan 09 '19 at 10:19

2 Answers2

3

This is probably due to the locale setting on your computer. You might provide a Locale when creating the DateTimeFormatter.

DateTimeFormatter ft = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.US);

This will ensure that the date is always parsed right.

Gilian Joosen
  • 486
  • 3
  • 21
2

This could be caused by your system locale not using Mon-Sun for week day short names, e.g. same exception will be thrown for German locale:

Locale.setDefault(Locale.GERMAN);
DateTimeFormatter ft = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy");
LocalDateTime.parse("Tue Jan 08 00:00:00 IST 2019", ft);

The code will work if you use the matching locale e.g. US:

Locale.setDefault(Locale.US);
DateTimeFormatter ft = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy");
LocalDateTime.parse("Tue Jan 08 00:00:00 IST 2019", ft);
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • 2
    Never set the default locale in some part of your code. That will break randomly. Use the DateTimeFormatter builder that takes a Locale as parameter – kumesana Jan 08 '19 at 16:09