SimpleDateFormatter not working correctly

I have the following code snippet.

@Override
    public String toString() {
        try {
            String calString = "Sat Sep 27 00:00:00 EDT 2014";
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY");
            System.out.println("calString " + calString);

            Date date = formatter.parse(calString);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            System.out.println("month " + calendar.get(Calendar.MONTH));
            System.out.println("day " + calendar.get(Calendar.DAY_OF_MONTH));
            DateFormat df = new SimpleDateFormat("YYYYMMdd");
            System.out.println("format date" + df.format(date));
            return df.format(date);
        } catch (ParseException ex) {
            return null;
        }
    }

Expected output should be 20140927

but I'm getting this instead.

calString Sat Sep 27 00:00:00 EDT 2014
month 0
day 3
format date 20140103

Anybody know why the day and month are off?

Jon Skeet
people
quotationmark

You're using YYYY instead of yyyy. That means "week year", to be used in conjunction with "week of year". Just change YYYY to yyyy in both of your SimpleDateFormat constructors and you'll get output of:

calString Sat Sep 27 00:00:00 EDT 2014
month 8
day 27
format date20140927

Note that month is 8 rather than 9 because months in java.util.Calendar are 0-based.

people

See more on this question at Stackoverflow