Parsing a java Date back from toString()
Solution 1
If you don't have control over the code that's generating the String:
To parse the toString()
format you need to set the SimpleDateFormat
locale to english and use the format: "EEE MMM dd HH:mm:ss Z yyyy"
.
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));`
Solution 2
I didn't test but something like this probably would work:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM HH:mm:ss z yyyy");
Date date = sdf.parse(dateStr);
If not, try to correct it using documentation: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString() http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
prepetti
Updated on July 09, 2022Comments
-
prepetti almost 2 years
I have a
String
containing the result oftoString()
called on an instance ofjava.util.Date
. How can I parse this value back to aDate
object?The Java docs say that
toString()
converts thisDate
object to aString
of the form:dow mon dd hh:mm:ss zzz yyyy
but of course there is no such format tag as
"dow"
or"mon"
.Could someone please help me with this problem. Please note that unfortunately the
toString()
call is in a piece of code out of my control. -
prepetti almost 12 yearsMm..as I said, I have no control over the toString(), since it is made by Struts. Anyway, setting the EN locale does the trick, so thank you. I just have to note that the right format string is "EEE MMM dd HH:mm:ss zzz yyyy", you had forgotten the Month.
-
Nuno Gonçalves almost 12 yearsI edited the answer to have it. :)
-
sizzle over 6 yearsThis does not work and results in an exception being thrown. The correct constructor call is:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));
-
Alex R almost 6 years"dow" and "mon" are not valid format specs