Search code examples
javacalendardayofweek

Java Calendar DAY_OF_WEEK SET to zero


I have this very old code block from PROD (>7 years) to be debugged. There's one point I couldnt understand. A section in the code does a calculation of next time a task will run and for tasks who need to run specifically on sunday, monday it uses Calendar.SUNDAY. But there's one statement whose behaviour I cannot interpret even after reading the docs multiple times

Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, 0);

since the days are numbered from 1-7 (Calendar.SUNDAY to Calendar.SATURDAY) that can be interpreted, but how does zero work here and why there is no exception?


Solution

  • why there is no exception?

    It is because you haven't set the lenient mode to false and it is true by default.

    Demo:

    import java.util.Calendar;
    
    public class Main {
        public static void main(String[] args) {
            Calendar cal = Calendar.getInstance();
            cal.setLenient(false);
            cal.set(Calendar.DAY_OF_WEEK, 0);
            System.out.println(cal.getTime());
        }
    }
    

    Output:

    Exception in thread "main" java.lang.IllegalArgumentException: DAY_OF_WEEK
    

    The documentation says:

    Any out of range values are either normalized in lenient mode or detected as an invalid value in non-lenient mode

    As part of the normalization, the value are rolled over e.g. the following code sets the value equivalent to cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY - 1):

    cal.set(Calendar.DAY_OF_WEEK, 0);
    

    Similarly, the following code sets the value equivalent to cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY - 2):

    cal.set(Calendar.DAY_OF_WEEK, -1);