javacalendardeprecatedjcalendar

How to fix deprecated .getDate()


I've been working on a project and in my private static class MyDateEvaluator , there's a deprecated api and that is getDate().

This is my first code:

    @Override
    public boolean isInvalid(Date date) {
    return date.getDay() == 0;
    }

Then I tried to change it to Calendar.get(Calendar.DAY_OF_MONTH), but it won't work and I get an error message,

MyDateEvaluator is not abstract.

    public boolean isInvalid(Calendar Calendar) {
        return 0 == Calendar.get(Calendar.DAY_OF_MONTH);

    }

Solution

  • 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.