Learn to determine, if the given year is leap year, using different Java date time classes including APIs introduced in Java 8.
1. Check leap year in Java 8
Given examples use the LocalDate.isLeapYear() and Year.isLeap() methods to determine if given date time instance is leap year or not.
We are using instances of ZonedDateTime, LocalDateTime, LocalDate and Year
classes from Java 8 date time APIs.
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Year; import java.time.ZonedDateTime; public class Main { public static void main(String[] args) { // 1. ZonedDateTime ZonedDateTime currentTime = ZonedDateTime.now(); if (currentTime.toLocalDate().isLeapYear()) { System.out.println(currentTime.getYear() + " is a leap year"); } else { System.out.println(currentTime.getYear() + " is NOT a leap year"); } // 2. LocalDateTime LocalDateTime localDateTime = LocalDateTime.now(); if (localDateTime.toLocalDate().isLeapYear()) { System.out.println(localDateTime.getYear() + " is a leap year"); } else { System.out.println(localDateTime.getYear() + " is NOT a leap year"); } // 3. LocalDate LocalDate localDate = LocalDate.now(); if (localDate.isLeapYear()) { System.out.println(localDate.getYear() + " is a leap year"); } else { System.out.println(localDate.getYear() + " is NOT a leap year"); } //4. Check current year is leap year or not if (Year.now().isLeap()) { System.out.println("Current year is a leap year"); } else { System.out.println("Current year is NOT a leap year"); } } }
Program output.
2019 is NOT a leap year 2019 is NOT a leap year 2019 is NOT a leap year Current year is NOT a leap year
2. Check leap year till Java 7
Before Java 8 release, primary classes to handle date and time were Date
, Calendar
and GregorianCalendar
. To determine the leap year, we have two approaches:
- GregorianCalendar.isLeapYear(int year)
- Custom method to determine leap year
No matter what approach we use, we must extract the year value from any given date or calendar instance and then use any of above methods.
import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { public static void main(String[] args) { // 1. Calendar Calendar cal = Calendar.getInstance(); System.out.println( isLeapYear(cal.get(Calendar.YEAR)) ); //2. Date Date date = new Date(); System.out.println( isLeapYear(date.getYear()) ); //3. GregorianCalendar GregorianCalendar gc = new GregorianCalendar(); System.out.println( gc.isLeapYear(gc.get(GregorianCalendar.YEAR)) ); } private static boolean isLeapYear(int year) { //1583 was the first year of the Gregorian Calendar assert year >= 1583; return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } }
Program output.
false false false
Happy Learning !!