javasimpledateformat

SimpleDateFormat timezone parsing


I'm having a tough time parsing this date its the +0 at the end that is causing a problem, does anyone know whats wrong with my format string?? If I remove the +0 from the date string and the Z from the format string it works fine, unfortunately for my application that isn't an option.

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SimpleDateFormat dateFormater = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss zZ");
        try {
            Date d = dateFormater.parse("Sun, 04 Dec 2011 18:40:22 GMT+0");
            System.out.println(d.toLocaleString());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Solution

  • If the format is that consistent, you could append 0:00 to the date string.

    String dateString = "Sun, 04 Dec 2011 18:40:22 GMT+0";
    SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss z", Locale.ENGLISH);
    Date date = sdf.parse(dateString + "0:00");
    System.out.println(date);
    

    (note that I fixed the SimpleDateFormat construction to explicitly specify the locale which would be used to parse the day of week and month names, otherwise it may fail on platforms which does not use English as default locale; I also wonder if you don't actually need HH instead of kk, but that aside)