Getting wrong data when using SimpleDateFormat.par

2019-06-15 20:17发布

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

2条回答
The star\"
2楼-- · 2019-06-15 20:32

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 :)

查看更多
淡お忘
3楼-- · 2019-06-15 20:33

Use this:

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

It's lower case y for year, not upper case Y. With that, the result is:

Wed Mar 11 12:00:12 EST 1992
Thu Mar 11 12:00:12 EST 1993
Fri Mar 11 12:00:12 EST 1994
Sat Mar 11 12:00:12 EST 1995

See here:

查看更多
登录 后发表回答