Strange behaviour with GregorianCalendar

后端 未结 8 1738
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 22:34

I just encountered a strange behaviour with the GregorianCalendar class, and I was wondering if I really was doing something bad.

This only appends when the initiali

8条回答
  •  有刺的猬
    2021-01-01 23:24

    Maybe setLenient(boolean lenient) will sort it out for you. I get an exception when I run the code below.

    If not, Joda is a better answer.

    import java.util.Calendar;
    
    public class CalTest
    {
        public static void main(String[] args)
        {
            // today is 2010/05/31
            Calendar cal = Calendar.getInstance();
            cal.setLenient(false);
    
            cal.set(Calendar.YEAR, 2010);
            cal.set(Calendar.MONTH, 1); // FEBRUARY
    
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
            cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
            cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
            cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
    
            System.out.println(cal.getTime());
        }
    }
    

提交回复
热议问题