I try to convert String to Date.
Here is my code:
SimpleDateFormat format = new SimpleDateFormat(\"EEE MMM dd HH:mm:ss zzz yyyy\");
Date da
The other answers were fine answers in 2012. Here’s an example of how to do with the modern (2014) Java date and time classes:
System.out.println("date de la requete est " + dateq);
DateTimeFormatter dtf = DateTimeFormatter
.ofPattern("EEE MMM dd HH:mm:ss xx uuuu", Locale.ROOT);
OffsetDateTime dateTime1 = OffsetDateTime.parse(dateq, dtf);
System.out.println("new date " + dateTime1);
The code example was inspired from a duplicate question (as I see it), How to convert Xml String date to int in java. With the example string from that question it prints:
date de la requete est Tue Feb 08 12:30:27 +0000 2011
new date 2011-02-08T12:30:27Z
Q: I cannot use the newer classes on Android(?)
A: Yes you can. For Android, use the backport specifically tailored to Android, ThreeTenABP. Otherwise for Java 6 and 7, use ThreeTen Backport.
Q: Your code doesn’t work for the date-time string in this question!
A: (1) If you can, avoid the three and four letter time zone abbreviations like CEST. Many are ambiguous and interpretation may even vary with your JVM’s current time zone setting. CEST is just the summer half of a time zone, not a full time zone. (2) If you cannot get a string without CEST
or similar in it, try using ZonedDateTime
instead of OffsetDateTime
and use zzz
in the format pattern as in the question. This works in the example and produces 2012-04-08T16:37+02:00[Europe/Paris]
.
Q: How do I use the newer classes?
A: One good place to start is the Oracle Tutorial.
Q: Locale.ROOT
??
A: If your date-time string comes from a specific place in the world and in the language of that place, use the corresponding locale, of course. If it’s just in English because computer systems everywhere tend to output English, I prefer to use Locale.ROOT
for “the locale neutral locale”, like saying “do not do anything locale-specific here”.
It looks like "Sun" isn't recognized. Try this:
date = format.parse("Sunday Apr 08 16:37:00 CEST 2012");
Works for me.
Either the code you posted is not your actual code, or you have a locale issue. It works fine on Sun Oracle Java 1.6 with a US locale.
Change your code to:
SimpleDateFormat format =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
SimpleDateFormat is Locale specific. At least the pattern E
and M
are locale specific, because for example "Sun" or "Sunday" will not match for Locale.GERMAN or Locale.FRENCH etc. You better specify the used Locale
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
or use a format, which is not locale specific.