LocalDateTime equals() method in Java



The equality of two LocalDateTime objects can be determined using the equals() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the LocalDateTime object to be compared. Also it returns true if both the LocalDateTime objects are equal and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
      LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30");
      System.out.println("The LocalDateTime ldt1 is: " + ldt1);
      System.out.println("The LocalDateTime ldt2 is: " + ldt2);
      boolean flag = ldt1.equals(ldt2);
      if(flag)
         System.out.println("\nBoth LocalDateTime objects are equal");
      else
         System.out.println("\nBoth LocalDateTime objects are not equal");
   }
}

Output

The LocalDateTime ldt1 is: 2019-02-18T23:15:30
The LocalDateTime ldt2 is: 2019-02-18T23:15:30
Both LocalDateTime objects are equal

Now let us understand the above program.

The two LocalDateTime objects are displayed. It is checked if the LocalDateTime objects are equal using the equals() method. The returned value of the method is displayed using an if statement. A code snippet that demonstrates this is as follows −

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The LocalDateTime ldt1 is: " + ldt1);
System.out.println("The LocalDateTime ldt2 is: " + ldt2);
boolean flag = ldt1.equals(ldt2);
if(flag)
   System.out.println("\nBoth LocalDateTime objects are equal");
else
   System.out.println("\nBoth LocalDateTime objects are not equal");
Updated on: 2019-07-30T22:30:25+05:30

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements