java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. For example:
LocalDate ld = LocalDate.now(ZoneId.systemDefault())
.with(DayOfWeek.TUESDAY);
System.out.println(ld);
When I ran this code today, Saturday, June 5, the output was:
2021-06-01
And yes, June 1 was Tuesday. Since we are passing an enum constant to with()
, there is really no possibility of passing an out-of-range value. DayOfWeek
is an enum holding 7 values for the 7 days of the week. Only trouble we can get ourselves into is by passing null
, which will throw a NullPointerException
, which I think you wanted.
If we do insist on passing the day of week as a number, that is possible, though. java.time numbers the days of the week from Monday = 1 through Sunday = 7.
LocalDate ld = LocalDate.now(ZoneId.systemDefault())
.with(ChronoField.DAY_OF_WEEK, 2);
So far the output is 2021-06-01
as before. But what if we pass 0?
.with(ChronoField.DAY_OF_WEEK, 0);
Exception in thread "main" java.time.DateTimeException: Invalid value
for DayOfWeek (valid values 1 - 7): 0
Not only do we get the exception you asked for, we are also getting a clear and helpful exception message, IMHO.
How does day of week zero work here?
With Calendar
day of week 0 works the same as 7 = Saturday. It seems that at least a lenient old-fashioned GregorianCalendar
performs a kind of modulo 7 operation on the day of week to bring it inside the interval 1 through 7. I did not find this documented. GregorianCalendar
is probably the concrete subclass of Calendar
that you are dealing with. I tried with different numbers that are all equivalent to 7 modulo 7:
int[] dows = { 0, 7, -7, 14, -14, -98 };
for (int dow : dows) {
Calendar cal = new GregorianCalendar(2021, Calendar.JUNE, 2);
Date dateBefore = cal.getTime();
cal.set(Calendar.DAY_OF_WEEK, dow);
System.out.format("%s and day of week %3d yields %s%n", dateBefore, dow, cal.getTime());
}
Output:
Wed Jun 02 00:00:00 CEST 2021 and day of week 0 yields Sat Jun 05 00:00:00 CEST 2021
Wed Jun 02 00:00:00 CEST 2021 and day of week 7 yields Sat Jun 05 00:00:00 CEST 2021
Wed Jun 02 00:00:00 CEST 2021 and day of week -7 yields Sat Jun 05 00:00:00 CEST 2021
Wed Jun 02 00:00:00 CEST 2021 and day of week 14 yields Sat Jun 05 00:00:00 CEST 2021
Wed Jun 02 00:00:00 CEST 2021 and day of week -14 yields Sat Jun 05 00:00:00 CEST 2021
Wed Jun 02 00:00:00 CEST 2021 and day of week -98 yields Sat Jun 05 00:00:00 CEST 2021
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.