javajodatimejava-time

Is there a java.time equivalent of DateTime.dayOfYear().isLeap()?


We have some code which checks whether a given day is a leap day using org.joda.time. It is simply

import org.joda.time.DateTime;

DateTime date;
return date.dayOfYear().isLeap()

Is there an equivalent in the java.time package that checks whether a given date is leap day?

I can't find the question asked anywhere on the site and hard-coding February 29 seems bad to me for some reason. I thought I was just overlooking something and thought this would be a good place to ask.

We only use the Gregorian (ISO 8601) calendar, though we do operate internationally.


Solution

  • Is the date February 29th?

    The java.time API only has the java.time.Year::isLeap method; no day-based isLeap method.

    If you want to find if a day is a leap day, then you can just check if the day is February 29th. That date only exists in a leap year.

    boolean isLeapDay(LocalDateTime dateTime) {
      return dateTime.getMonth() == Month.FEBRUARY 
          && dateTime.getDayOfMonth() == 29;
    }
    

    Alternatively, use MonthDay class, with MonthDay.of ( Month.FEBRUARY , 29 ).

    LocalDate today = LocalDate.now ( ZoneId.of ( "America/Edmonton" ) );
    boolean isLeapDay = MonthDay.from ( today ).equals ( MonthDay.of ( Month.FEBRUARY , 29 ) );