LocalDateTime compareTo() method in Java

Java 8Object Oriented ProgrammingProgramming

Two LocalDateTime objects can be compared using the compareTo() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the LocalDateTime object to be compared.

If the first LocalDateTime object is greater than the second LocalDateTime object it returns a positive number, if the first LocalDateTime object is lesser than the second LocalDateTime object it returns a negative number and if both the LocalDateTime objects are equal it returns zero.

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-15T11:37:12");
      LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30");
      System.out.println("The first LocalDateTime object is: " + ldt1);
      System.out.println("The second LocalDateTime object is: " + ldt2);
      int val = ldt1.compareTo(ldt2);
      if(val > 0)
         System.out.println("\nThe first LocalDateTime object is greater than the second LocalDateTime object");
      else if(val < 0)
         System.out.println("\nThe first LocalDateTime object is lesser than the second LocalDateTime object");
      else
         System.out.println("\nThe LocalDateTime objects are equal");
   }
}

Output

The first LocalDateTime object is: 2019-02-15T11:37:12
The second LocalDateTime object is: 2019-02-18T23:15:30
The first LocalDateTime object is lesser than the second LocalDateTime object

Now let us understand the above program.

First the two LocalDateTime objects are displayed. Then they are compared using the compareTo() method and the result is displayed using if else statement. A code snippet that demonstrates this is as follows −

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-15T11:37:12");
LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The first LocalDateTime object is: " + ldt1);
System.out.println("The second LocalDateTime object is: " + ldt2);
int val = ldt1.compareTo(ldt2);
if(val > 0)
   System.out.println("\nThe first LocalDateTime object is greater than the second LocalDateTime object");
else if(val < 0)
   System.out.println("\nThe first LocalDateTime object is lesser than the second LocalDateTime object");
else
   System.out.println("\nThe LocalDateTime objects are equal");
raja
Published on 27-Mar-2019 06:06:33
Advertisements