Checking for a Leap Year using GregorianCalendar in Java



The GregorianCalendar.isLeapYear() method determines if the given year is a leap year. Returns true if the given year is a leap year.

Firstly, import the following package to work with GregorianCalendar class.

import java.util.GregorianCalendar;

Now, check for a year by adding it as a parameter in the isLeapYear() method.

gcal.isLeapYear(2012)

The following is an example.

Example

 Live Demo

import java.text.ParseException;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String[] args) throws ParseException {
      GregorianCalendar gcal = new GregorianCalendar();
      System.out.println("Is it a leap year? "+gcal.isLeapYear(2012));
   }
}

Output

Is it a leap year? true

Let us see another example.

Example

 Live Demo

import java.text.ParseException;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String[] args) {
      GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar.getInstance();
      System.out.println("Current date-time = " + calendar.getTime());
      boolean res = calendar.isLeapYear(calendar.get(GregorianCalendar.YEAR));
      System.out.println("Is it a leap year? " + res);
   }
}

Output

Current date-time = Mon Nov 19 15:45:30 UTC 2018
Is it a leap year? false
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements