Signup/Sign In
LAST UPDATED: JUNE 15, 2020

Java LocalDate CompareTo() Method

The compareTo() method is used to compare a date with another date. It returns an integer value and takes an instance of CronoLocalDate as an argument. This method is useful for comparing two dates in Java application. Syntax of the method is given below.

Syntax

public int compareTo(ChronoLocalDate otherdate)

Parameters

otherdate: Another date which is to be compared

Returns

It returns negative if date is less else positive if greater

Example:

The compareTo() method returns negative integer if the specified date is less than the date. In this example we have two dates and using compareTo() to check whether the specified date is older to other on not.

import java.time.LocalDate;

public class Demo {  
	public static void main(String[] args){  
		
		// Take a date
		LocalDate localDate1 = LocalDate.of(2018, 2, 20);
		// Displaying date
		System.out.println("First Date is : "+localDate1);
		// Take another date
		LocalDate localDate2 = LocalDate.of(2018, 2, 22);
		// Displaying date
		System.out.println("Another Date is : "+localDate2);
		// Using compareTo() method
		int val = localDate1.compareTo(localDate2);
		System.out.println(val);
	}
}


First Date is : 2018-02-20
Another Date is : 2018-02-22
Date with local time: -2

Example:

If the specified date is greater than the date then it returns a positive integer. You can notice that the below example returns positive integer which is difference of both dates.

import java.time.LocalDate;

public class Demo {  
	public static void main(String[] args){  
		
		// Take a date
		LocalDate localDate1 = LocalDate.of(2018, 2, 20);
		// Displaying date
		System.out.println("First Date is : "+localDate1);
		// Take another date
		LocalDate localDate2 = LocalDate.of(2018, 2, 22);
		// Displaying date
		System.out.println("Another Date is : "+localDate2);
		// Using compareTo() method
		int val = localDate2.compareTo(localDate1);
		System.out.println(val);
	}
}


First Date is : 2018-02-20
Another Date is : 2018-02-22
2

Live Example:

Try with a live example, execute the code instantly with our powerful Online Java Compiler.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.