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?
Compare two ZonedDateTime objects for Ordering using compareTo() method. In Java, to compare two ZonedDateTime objects for ordering we can use the ZonedDateTime . compareTo() method which return int value of -1, 0 or 1 if the ZonedDateTime object is before, equal to or after the ZonedDateTime object it compare to.
minus() method of a ZonedDateTime class used to returns a copy of this date-time with the specified amount subtracted to date-time. The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.
ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times.
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 it'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
ZonedDateTime implements Comparable
interface so you can simple use Collections.max
Collections.max(Arrays.asList(a,b));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With