Calculate leap year

This example will show how to determine if the given year is a leap year demonstrating java GregorianCalendar.isLeapYear, java 8 date time api Year.isLeap and joda DateTime.withYear.year().isLeap().

Straight up Java

Calendar

@Test
public void calculate_leap_year_in_java_with_calendar () {

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.YEAR, 2007);

      assertFalse(cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365);
}

Gregorian calendar

@Test
public void calculate_leap_year_in_java_with_gregorian_calendar () {

    GregorianCalendar cal = new GregorianCalendar();
    assertFalse(cal.isLeapYear(2007));
}

Java 8 Date and Time API

@Test
public void calculate_leap_year_in_java_with_java8_date_time () {

    boolean validLeapYear = Year.of(2007).isLeap();

    assertFalse(validLeapYear);

    // or 

    boolean isLeapYear = LocalDate.ofYearDay(2007, 1).isLeapYear();

    assertFalse(isLeapYear);
}

Joda Time

@Test
public void calculate_leap_year_in_java_with_joda () {

    DateTime dateTime = new DateTime();
    boolean isLeapYear = dateTime.withYear(2007).year().isLeap();

    assertFalse(isLeapYear);
}