Getting wrong data when using SimpleDateFormat.parse()

Tegi picture Tegi · Mar 23, 2012 · Viewed 7.8k times · Source

I am getting the strangest error, when trying to parse a string as a calendar. It seems that it messes up the Date object which I use to set the result calendar's time. The error is pretty inconsistent (or I see no logic in it). Can anyone point out what I might be doing wrong ?

public class caltest{
public static final SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss.SSS");

public static void main(String[] args) {
    String date1 = "1992-03-11 12:00:12.123";
    String date2 = "1993-03-11 12:00:12.123";
    String date3 = "1994-03-11 12:00:12.123";
    String date4 = "1995-03-11 12:00:12.123";
    parseStringAsCalendar(date1);
    parseStringAsCalendar(date2);
    parseStringAsCalendar(date3);
    parseStringAsCalendar(date4);
}
public static String calendarToString(Calendar cal) {
    return sdf.format(cal.getTime());
}

public static Calendar parseStringAsCalendar(String s) {
    Date time = null;
    try {
        time = sdf.parse(s);
    } catch (ParseException e) {
        System.out.println("Exception");
        e.printStackTrace();
    }
    System.out.println(time.toString());
    GregorianCalendar ret = new GregorianCalendar();
    ret.setTime(time);

    return ret;
}

}

The output is :

Sun Dec 29 12:00:12 CET 1991
Sun Dec 27 12:00:12 CET 1992
Sun Dec 26 12:00:12 CET 1993
Sun Jan 01 12:00:12 CET 1995

Answer

Jon Skeet picture Jon Skeet · Mar 23, 2012

You're using YYYY in your format specifier, which is week year (as of Java 7, I believe). You want yyyy, which is just "year". (See the SimpleDateFormat documentation.)

I suspect the rest of the date was out because you tried to also specify the month and day, which aren't really "features" in the week year... if you'd specified the "week of week year" and day of week, it might have given some more sensible results, but only if you really meant to use week years, which I doubt :)