尝试将字符串解析为日历时,我遇到了最奇怪的错误。似乎它弄乱了我用来设置结果日历时间的 Date 对象。该错误非常不一致(或者我看不到其中的逻辑)。谁能指出我可能做错了什么?
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;
}
}
输出是:
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