How parse 2013-03-13T20:59:31+0000 date string to Date

Haris Dautović picture Haris Dautović · Mar 15, 2013 · Viewed 75.5k times · Source

How to parse this format date string 2013-03-13T20:59:31+0000 to Date object?

I'm trying on this way but it doesn't work.

DateFormat df = new SimpleDateFormat("YYYY-MM-DDThh:mm:ssTZD");
Date result =  df.parse(time);

Answer

msam picture msam · Mar 15, 2013

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");

Year is lower case y. Any characters that are in the input which are not related to the date (like the 'T' in 2013-03-13T20:59:31+0000 should be quoted in ''.

For a list of the defined pattern letters see the documentation

Parse checks that the given date is in the format you specified. To print the date in a specific format after checking see below:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
Date result;
try {
    result = df.parse("2013-03-13T20:59:31+0000");
    System.out.println("date:"+result); //prints date in current locale
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(sdf.format(result)); //prints date in the format sdf
}