Java compare localdate: In this article we are going to see the use of Java LocalDate class compareTo( ) method with suitable examples.
Java LocalDate compareTo( ) Method with Example
This java.time.LocalDate.compareTo(ChronoLocalDate other) method is used to compare a date with another date. It returns comparator value, gives negative if less, positive if greater.
Syntax:
public int compareTo(ChronoLocalDate other)
Where,
otherrefers to the other date to be compared.
Let’s see a program to understand it more clearly.
- CASE-1: When the second date is greater than first date
- CASE-2: When the second date is less than first date
Approach:
- Create two objects of LocalDate class which will hold the parsed dates, here we have taken
date1anddate2. - Then by using
compareTo()method compare two dates likedate2.compareTo(date1) - Print the final result.
Program:(CASE-1: When the second date is greater than first date)
import java.time.LocalDate;
public class Main
{
public static void main(String[] args)
{
//Create an object of LocalDate class and assign a date to it
LocalDate date1 = LocalDate.parse("2022-04-25");
System.out.println("date-1: "+date1);
//Create an object of LocalDate class and assign a date to it
LocalDate date2 = LocalDate.parse("2022-05-08");
System.out.println("date-2: "+date2);
//Pass both the date into method and compare both the values and print the final result
//it will return positive value as date2 is greater than date1
System.out.println("Compared value: "+date2.compareTo(date1));
}
}
Output: date-1: 2022-04-25 date-2: 2022-05-08 Compared value: 1
Program:(CASE-2: When the second date is less than first date)
import java.time.LocalDate;
public class Main
{
public static void main(String[] args)
{
//Create an object of LocalDate class and assign a date to it
LocalDate date1 = LocalDate.parse("2022-04-25");
System.out.println("date-1: "+date1);
//Create an object of LocalDate class and assign a date to it
LocalDate date2 = LocalDate.parse("2022-05-08");
System.out.println("date-2: "+date2);
//Pass both the date into method and compare both the values and print the final result
//it will return positive value as date1 is less than date2
System.out.println("Compared value: "+date1.compareTo(date2));
}
}
Output: date-1: 2022-04-25 date-2: 2022-05-08 Compared value: -1
Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.