- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
Advertisements