How to check Leap Year in Java 8 How to get current timestamp in Java 8?


The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.

Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.

The isLeapYear() method of java.time.LocalDate verifies if the year in the current object is a leap year according to the ISO proleptic calendar system rules, returns true if so, else returns false.

Example

Following Java program gets the current date and finds out whether it is a leap year.

import java.time.LocalDate;
public class IsLeapYear {
   public static void main(String args[]) {
      //Getting the current date
      LocalDate currentDate = LocalDate.now();
      //Verifying if leap year
      boolean bool = currentDate.isLeapYear();
      //is after
      if(bool){
         System.out.println("Current year is a leap year ");
      }else{
         System.out.println("Current year is not a leap year ");
      }
   }
}

Output

Current year is not a leap year

Example

Following example accepts an year from user and displays whether it is a leap year.

import java.time.LocalDate;
import java.util.Scanner;
public class IsLeapYear {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      //Getting the date of jan1st of the given date value
      LocalDate givenDate = LocalDate.of(year, 01, 01);
      //Verifying if leap year
      boolean bool = givenDate.isLeapYear();
      //is after
      if(bool){
         System.out.println("Given year is a leap year ");
      }else{
         System.out.println("Given year is not a leap year ");
      }
   }
}

Output

Enter the year:
2004
Given year is a leap year

Updated on: 07-Aug-2019

722 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements