LocalDate compareTo() method


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

If the first LocalDate object is greater than the second LocalDate object it returns a positive number, if the first LocalDate object is lesser than the second LocalDate object it returns a negative number and if both the LocalDate 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) {
      LocalDate ld1 = LocalDate.parse("2019-02-15");
      LocalDate ld2 = LocalDate.parse("2019-02-12");
      System.out.println("The first LocalDate object is: " + ld1);
      System.out.println("The second LocalDate object is: " + ld2);
      int val = ld1.compareTo(ld2);
      if(val > 0)
         System.out.println("
The first LocalDate object is greater than the second LocalDate object");       else if(val < 0)          System.out.println("
The first LocalDate object is lesser than the second LocalDate object");       else          System.out.println("
The LocalDate objects are equal");    } }

Output

The first LocalDate object is: 2019-02-15
The second LocalDate object is: 2019-02-12
The first LocalDate object is greater than the second LocalDate object

Now let us understand the above program.

First the two LocalDate 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 −

LocalDate ld1 = LocalDate.parse("2019-02-15");
LocalDate ld2 = LocalDate.parse("2019-02-12");
System.out.println("The first LocalDate object is: " + ld1);
System.out.println("The second LocalDate object is: " + ld2);
int val = ld1.compareTo(ld2);
if(val > 0)
   System.out.println("
The first LocalDate object is greater than the second LocalDate object"); else if(val < 0)    System.out.println("
The first LocalDate object is lesser than the second LocalDate object"); else    System.out.println("
The LocalDate objects are equal");

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements