java.time
I suggest:
Set<DayOfWeek> invalidDays = EnumSet.of(DayOfWeek.SUNDAY);
@Override
public boolean isInvalid(Date date) {
// First convert to a modern type
ZonedDateTime zdt = date.toInstant().atZone(ZoneId.systemDefault());
DayOfWeek dow = zdt.getDayOfWeek();
return invalidDays.contains(dow);
}
It would be still better if you could avoid the old-fashioned Date
class completely. I have assumed that the method signature is in an interface or superclass that you cannot change. If so, the parameter does need to have type Date
, we cannot substitute with LocalDate
(nor with Calendar
as you tried).
Both Date
and Calendar
are poorly designed and long outdated. So the best thing we can do when we get a Date
is convert it to an Instant
and perform any further conversions from there. My code depends on the JVM’s default time zone, which is shaky because the setting can be changed at any time. However, given the poor design of the Date
class there is no way we can avoid this.
An option that is a bit simpler than the above and may be good enough would be to declare DayOfWeek invalidDay = DayOfWeek.SUNDAY;
instead of the set and compare using .equals
.