In this post, we will demonstrate how to compare LocalDateTime objects in Java with an example.
LocalDateTime class provides below APIs compare LocalDateTime objects in Java.
LocalDateTime APIs to Compare LocalDateTime Objects in Java
- boolean isAfter(ChronoLocalDateTime<?> other) - Checks if this date-time is after the specified date-time.
- boolean isBefore(ChronoLocalDateTime<?> other) - Checks if this date-time is before the specified date-time.
- boolean isEqual(ChronoLocalDateTime<?> other) - Checks if this date-time is equal to the specified date-time.
- int compareTo(ChronoLocalDateTime<?> other) - Compares this date-time to another date-time.
Example
import java.time.LocalDateTime;
/**
* Program to demonstrate LocalDateTime Class APIs.
* @author javaguides.net
*
*/
public class LocalDateTimeExample {
public static void main(String[] args) {
compareLocalDateTimeObjects();
}
private static void compareLocalDateTimeObjects() {
LocalDateTime dateTime1 = LocalDateTime.of(2017, 05, 22, 10, 55, 25);
LocalDateTime dateTime2 = LocalDateTime.of(2017, 06, 11, 05, 35, 26);
LocalDateTime dateTime3 = LocalDateTime.of(2017, 05, 22, 10, 55, 25);
// Using isBefore() method
if (dateTime1.isBefore(dateTime2)) {
System.out.println("dateTime1 is before dateTime2");
}
// Using isAfter() method
if (dateTime2.isAfter(dateTime3)) {
System.out.println("dateTime2 is after dateTime3");
}
// Using isEqual() method
if (dateTime1.isEqual(dateTime3)) {
System.out.println("dateTime1 is equal to dateTime3");
}
// Using compareTo() method
if (dateTime1.compareTo(dateTime3) == 0) {
System.out.println("dateTime1 is equal to dateTime3");
}
}
}
Output:
dateTime1 is before dateTime2
dateTime2 is after dateTime3
dateTime1 is equal to dateTime3
dateTime1 is equal to dateTime3
Comments
Post a Comment