Code Junkie
Code Junkie

Reputation: 7788

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?

Upvotes: 1

Views: 131

Answers (3)

SparkOn
SparkOn

Reputation: 8946

A little more healthy solution

SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"
                                                                ,Locale.ENGLISH);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499790

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.

Upvotes: 4

Reimeus
Reimeus

Reputation: 159754

Y represents week year. y is used to match the year

SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

Upvotes: 10

Related Questions