1

I'm trying to parse this string in the following way but I get an exception. Can anyone help me please?

String dateStr = "Thu 14 Feb 2019 15:05:48 +0200";
LocalDateTime datetime = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("EEE d MMM yyyy HH:mm:ss Z"));

Exception:

java.time.format.DateTimeParseException: Text 'Thu 14 Feb 2019 15:05:48 +0200' could not be parsed at index 0
Simone
  • 21
  • 1
  • 3
  • 3
    You put wrong code I guess. You want to parse oldDate but your variable is dateStr it means that you want to format date using this patter but your String doesn't match that. Show how oldDate looks like – Rafał Sokalski Feb 15 '19 at 11:55
  • 1
    @RafałSokalski Then why did OP get that error message? – Joakim Danielson Feb 15 '19 at 11:57
  • 2
    What is your locale? `Thu` probably needs English. – Thilo Feb 15 '19 at 11:58
  • 1
    @RafałSokalski is indeed right. You're putting the `oldDate` into it, instead of the `dateStr`. With the `oldDate` replaced with `dateStr`, [it's working as expected](https://tio.run/##ZU/LasMwELz7KwafbNoKOSTQ2vRWhxxqKCSnlh4UW2nlWpaR1oFQ8u2uojSHkL3sY2Z2Z1uxFw9t8zNNSg/GElo/YKS0ZK@mFt2LILnxXRHd4DtjtSB2YSxDS9IWUd0J51AJ1f9GwDBuO1XDkSCf9kY10B5K1mRV//XxCZGeaMB5gMYv9CWeEW@@R2RzLOUWM549IVvkfJHPH3HHZ5zHRZBd@Qzqkz0vvwLYIKyTyf/ye9zYZmb3Foo@icuyRIOqqnDwgdUq1zr3L73HaXo@uj44kpqZkdjgXVPXJ5fLgXGMjtP0Bw). So the `oldDate`-String probably is in a different format. What is the value of `oldDate`? – Kevin Cruijssen Feb 15 '19 at 11:58
  • 2
    This works `LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("EEE d MMM yyyy HH:mm:ss Z", Locale.ENGLISH));` – David Pérez Cabrera Feb 15 '19 at 12:01
  • Try it with `DateTimeFormatter.ofPattern("EEE d MMM yyyy HH:mm:ss Z",Locale.US)` if your locale is not English. – Eritrean Feb 15 '19 at 12:03
  • Besides a locale, an OffsetDateTime, even much better a ZonedDateTime should used to not lose +0200. – Joop Eggen Feb 15 '19 at 12:23
  • 1
    Thank you all! The issue was related to the Local. Inserting Locale.US as @Eritrean says it works correctly. – Simone Feb 15 '19 at 13:33

2 Answers2

1
String dateStr = "Thu 14 Feb 2019 15:05:48 +0200";
        Locale bLocale = new Locale.Builder().setLanguage("en").setRegion("US").build();
        LocalDateTime datetime = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("EEE d MMM yyyy HH:mm:ss Z", bLocale));
        System.out.println(datetime);

You should create a locale as the parameter.

flycash
  • 414
  • 4
  • 8
0

I'm not sure, but I think EEE only works if you specify locale. Anyway, it will work if you just ignore the day of the month.

LocalDateTime datetime = LocalDateTime.parse(
    dateStr.substring(4), // skip "Thu "
    DateTimeFormatter.ofPattern("d MMM yyyy HH:mm:ss Z"));
Leo Aso
  • 11,898
  • 3
  • 25
  • 46