- 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
LocalDateTime compareTo() method in Java
Two LocalDateTime objects can be compared using the compareTo() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the LocalDateTime object to be compared.
If the first LocalDateTime object is greater than the second LocalDateTime object it returns a positive number, if the first LocalDateTime object is lesser than the second LocalDateTime object it returns a negative number and if both the LocalDateTime 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) { LocalDateTime ldt1 = LocalDateTime.parse("2019-02-15T11:37:12"); LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30"); System.out.println("The first LocalDateTime object is: " + ldt1); System.out.println("The second LocalDateTime object is: " + ldt2); int val = ldt1.compareTo(ldt2); if(val > 0) System.out.println("
The first LocalDateTime object is greater than the second LocalDateTime object"); else if(val < 0) System.out.println("
The first LocalDateTime object is lesser than the second LocalDateTime object"); else System.out.println("
The LocalDateTime objects are equal"); } }
Output
The first LocalDateTime object is: 2019-02-15T11:37:12 The second LocalDateTime object is: 2019-02-18T23:15:30 The first LocalDateTime object is lesser than the second LocalDateTime object
Now let us understand the above program.
First the two LocalDateTime 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 −
LocalDateTime ldt1 = LocalDateTime.parse("2019-02-15T11:37:12"); LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30"); System.out.println("The first LocalDateTime object is: " + ldt1); System.out.println("The second LocalDateTime object is: " + ldt2); int val = ldt1.compareTo(ldt2); if(val > 0) System.out.println("
The first LocalDateTime object is greater than the second LocalDateTime object"); else if(val < 0) System.out.println("
The first LocalDateTime object is lesser than the second LocalDateTime object"); else System.out.println("
The LocalDateTime objects are equal");