- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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");
To Continue Learning Please Login
Login with Google