Strange behaviour with GregorianCalendar

后端 未结 8 1740
没有蜡笔的小新
没有蜡笔的小新 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

    Yes, this is how it is intended to work. If you start from a GregorianCalendar that has a precise date and you modify it by making it inconsistent then you shouldn't trust the results you obtain.

    According to the documentation about getActualMaximum(..) it states:

    For example, if the date of this instance is February 1, 2004, the actual maximum value of the DAY_OF_MONTH field is 29 because 2004 is a leap year, and if the date of this instance is February 1, 2005, it's 28.

    So it is supposed to work but you have to feed it with consistent values. 31 February 2010 is not correct and applying things that relies on the date value (like getActualMaximum) can't work. How should it fix it by itself? By deciding that month is wrong? or that the day is wrong?

    By the way, as everyone always states use JodaTime.. :)

    0 讨论(0)
  • 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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题