The method compareTo() compares two dates and returns an integer value based on the comparison.
Method Signature:
public int compareTo(ChronoLocalDate otherDate)
It returns 0 if both the dates are equal.
It returns positive value if “this date” is greater than the otherDate.
It returns negative value if “this date” is less than the otherDate.
LocalDate compareTo() Example
import java.time.LocalDate; public class Example { public static void main(String[] args) { /* Comparing the Dates given in String format * First the given strings are parsed in the LocalDate * and then compared against each other using compareTo() */ LocalDate date1 = LocalDate.parse("2017-06-22"); System.out.println(date1); LocalDate date2 = LocalDate.parse("2017-06-22"); System.out.println(date2); System.out.println(date2.compareTo(date1)); /* Comparing the Dates with the given year, month and * day information. The given data is passed in the of() method * of LocalDate to create instances of LocalDate and then compared * using the compareTo() method. * */ LocalDate date3 = LocalDate.of(2017, 06, 22); System.out.println(date3); LocalDate date4 = LocalDate.of(2017, 10, 26); System.out.println(date4); System.out.println(date4.compareTo(date3)); /* Given Date is compared with the current Date */ LocalDate date5 = LocalDate.now(); System.out.println(date5); LocalDate date6 = LocalDate.of(2016, 02, 10); System.out.println(date6); System.out.println(date6.compareTo(date5)); } }
Output:
2017-06-22 2017-06-22 0 2017-06-22 2017-10-26 4 2017-10-28 2016-02-10 -1
As you can see that the first comparison resulted 0 because both the dates are equal. The second comparison resulted positive value because “this date”(date 4) is greater than the “other date”(date3). The third comparison resulted negative value because “this date”(date 6) is less than the “other date”(date5).
Leave a Reply