javajava-streamcomparatordate-comparisonzoneddatetime

How to get the maximum of two ZonedDateTime instances?


I have two ZonedDateTime instances:

final ZonedDateTime a = ...;
final ZonedDateTime b = ...;

I want to get the maximum of those two values. I want to avoid having to write custom ad-hoc code.

What is the best way to do this in Java 8? I am currently doing it as following:

final ZonedDateTime c = Stream.of(a, b).max(ChronoZonedDateTime::compareTo).get();

Are there better approaches?


Solution

  • You can simply call isAfter:

    ZonedDateTime max = a.isAfter(b) ? a : b;
    

    or since the class implements Comparable:

    a.compareTo(b);
    

    As pointed out by OleV.V. in the comments, there's a difference between the two methods for comparing times. So they might produce different results for the same values

    DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
    ZonedDateTime time1 = ZonedDateTime.from(formatter.parse("2019-10-31T02:00+01:00"));
    ZonedDateTime time2 = ZonedDateTime.from(formatter.parse("2019-10-31T01:00Z"));
    
    System.out.println(time1.isAfter(time2) + " - " + time1.isBefore(time1) + " - " + time1.isEqual(time2));
    System.out.println(time1.compareTo(time2));
    

    Generates

    false - false - true
    1