1

So I get this String ("Tue Nov 26 12:05:19 CET 2019") from a txt fiel and I want to parse it into a Date like this:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date date = null;

try {
    date = format.parse(dateAsString);
} catch (ParseException e) {
    e.printStackTrace();
}

And I still get this Exception:

java.text.ParseException: Unparseable date: "Tue Nov 26 12:05:19 CET 2019"

But the format/patter should be ok. So my question is how I parse the string into a date.

Kiwanga
  • 65
  • 1
  • 5
  • 3
    What is your JVM and operating system locale? Could it be that it's not English so `Tue` and `Nov` are not parsed? – Karol Dowbecki Nov 26 '19 at 11:17
  • Can you update your entire code? I tried doing the same but it was working fine. – Dinesh Shekhawat Nov 26 '19 at 11:23
  • What do you get if you run this line of code: `System.out.println(java.util.Locale.getDefault());` – Abra Nov 26 '19 at 11:30
  • See this question https://stackoverflow.com/questions/19861642/date-format-parse-exception-eee-mmm-dd-hhmmss-z-yyyy – Nick Nov 26 '19 at 11:32
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 27 '19 at 06:25

3 Answers3

3

You are most likely not using English locale so Tue and Nov are not parsing. Specify the locale with the formatter and don't use obsolete date classes:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
ZonedDateTime time = ZonedDateTime.parse("Tue Nov 26 12:05:19 CET 2019", fmt);
System.out.println(time); // 2019-11-26T12:05:19+01:00[Europe/Paris]
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • You assume the OP is using at least JDK 1.8. Also it's not clear to me from your answer that the code you posted is using the new Date-Time API that was added in JDK 1.8 – Abra Nov 26 '19 at 11:27
1

you can set language as English here

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
Date date = null;

try {
    date = format.parse("Tue Nov 26 12:05:19 CET 2019");
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(date);
Bentaye
  • 9,403
  • 5
  • 32
  • 45
0

This worked for me:

SimpleDateFormat format = 
    new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy", new Locale("en", "EN"));
Bentaye
  • 9,403
  • 5
  • 32
  • 45