How to check if two dates are equal in Java 8?

Java 8Object Oriented ProgrammingProgramming

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 of() method of the java.time.LocalDate class accepts three integer parameters representing and year, a month of an year, day of a month and, returns the instance of the LocalDate object from the given details.

The now() method of the java.time.LocalDate obtains and returns the current date from the system clock.

The equals() method of the java.time.LocalDate class accepts an object (representing a LocalDate ) and compares it with the current LocalDate object, if both are equal this method returns true else it returns false. If the object you pass to this method is not of type LocalDate this method returns false.

Example

Following Java example reads date values from user and constructs a LocalDate instance. Retrieves the current Date and compares these two values and prints the result.

import java.time.LocalDate;
import java.util.Scanner;
public class LocalDateJava8 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      System.out.println("Enter the month: ");
      int month = sc.nextInt();
      System.out.println("Enter the day: ");
      int day = sc.nextInt();
      //Getting the current date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      System.out.println("Date: "+givenDate);
      //Retrieving the current date
      LocalDate currentDate = LocalDate.now();
      //Comparing both values
      boolean bool = givenDate.equals(currentDate);
      if(bool) {
         System.out.println("Given date is equal to the current date ");
      }else {
         System.out.println("Given date is not equal to the current date ");
      }
   }
}

Output

Enter the year:
2019
Enter the month:
07
Enter the day:
24
Date: 2019-07-24
Given date is equal to the current date
raja
Published on 07-Aug-2019 11:10:02
Advertisements