Search code examples
javastringdatesimpledateformat

Parse a String to Date in Java


I'm trying to parse a string to a date, this is what I have:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zZ (zzzz)");
Date date = new Date();
try {
    date = sdf.parse(time);
} catch (ParseException e) {
    e.printStackTrace();
}

the string to parse is this:

Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time)

I followed the http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Pretty sure I've done everything by the book. But it is giving me ParseException.

java.text.ParseException: Unparseable date: 
"Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time)"

What am I doing wrong? Patterns I Have tried:

EEE MMM dd yyyy HH:mm:ss zzz
EEE MMM dd yyyy HH:mm:ss zZ (zzzz)

Solution

  • You seem to be mixing the patterns for z and Z. If you ignore the (FLE Daylight Time), since this is the same info as in GMT+0300, the problem becomes that SimpleDateFormat wants either GMT +0300 or GMT+03:00. The last variant can be parsed like this:

    String time = "Sun Jul 15 2012 12:22:00 GMT+03:00 (FLE Daylight Time)";
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz");
    Date date = sdf.parse(time);
    

    [EDIT]
    In light of the other posts about their time strings working, this is probably because your time string contains conflicting information or mixed formats.