Compare ZonedDateTime Objects in Java

Compare ZonedDateTime Objects in Java

ZonedDateTime class provides below APIs to compare ZonedDateTime objects in Java.
Methods inherited from interface java.time.chrono.ChronoZonedDateTime
  • default boolean isAfter(ChronoZonedDateTime<?> other) - Checks if the instant of this date-time is after that of the specified date-time.
  • default boolean isBefore(ChronoZonedDateTime<?> other) - Checks if the instant of this date-time is before that of the specified date-time.
  • default boolean isEqual(ChronoZonedDateTime<?> other) - Checks if the instant of this date-time is equal to that of the specified date-time.
  • default int compareTo(ChronoZonedDateTime<?> other) - Compares this date-time to another date-time, including the chronology.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Program to demonstrate ZonedDateTime Class APIs.
 * @author javaguides.net
 *
 */
public class ZonedDateTimeExample {
 
    public static void main(String[] args) {
        compareZonedDateTimeObjects();
    }

    private static void compareZonedDateTimeObjects() {
        LocalDateTime dateTime = LocalDateTime.now();

        ZonedDateTime dt1 = ZonedDateTime.of(dateTime, ZoneId.of("America/New_York"));
        ZonedDateTime dt2 = ZonedDateTime.of(dateTime, ZoneId.of("America/New_York"));
        ZonedDateTime dt3 = ZonedDateTime.of(dateTime, ZoneId.of("UTC"));
  
        // Using isEqual()
        if (dt1.isEqual(dt2)) {
             System.out.println("dateTime1 and dateTime2 are equal.");
        } else {
             System.out.println("dateTime1 and dateTime2 are not equal.");
        }

        // Using compareTo()
        if (dt1.compareTo(dt2) == 0) {
            System.out.println("dateTime1 and dateTime2 are equal.");
        } else {
            System.out.println("dateTime1 and dateTime2 are not equal.");
        }

         // Using isAfter()
        if (dt2.isAfter(dt3)) {
           System.out.println("dateTime2 is after dateTime3");
        }   

        // Using isBefore()
        if (dt3.isBefore(dt1)) {
            System.out.println("dateTime3 is before dateTime1");
        }
    }
}
Output:
dateTime1 and dateTime2 are equal.
dateTime1 and dateTime2 are equal.
dateTime2 is after dateTime3
dateTime3 is before dateTime1

Reference


Comments