Why does a new SimpleDateFormat object contain calendar with the wrong year?

后端 未结 5 583
暖寄归人
暖寄归人 2020-12-20 15:54

I came upon a strange behavior that has left me curious and without a satisfactory explanation as yet.

For simplicity, I\'ve reduced the symptoms I\'ve noticed to th

5条回答
  •  北海茫月
    2020-12-20 16:05

    SimpleDateFormat has mutable internal state. This is why I avoid it like the plague (I recommend Joda Time). This internal calendar is probably used during the process of parsing a date, but there's no reason it would be initialized to anything in particular before it has parsed a date.

    Here's some code to illustrate:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.GregorianCalendar;
    
    public class DateTest {
        public static void main(String[] args) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
            System.out.println("sdf cal: " + simpleDateFormat.getCalendar());
            System.out.println("new cal: " + new GregorianCalendar());
            System.out.println("new date: " + simpleDateFormat.format(new Date()));
            System.out.println("sdf cal: " + simpleDateFormat.getCalendar());
        }
    }
    

提交回复
热议问题