Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
thatsme Avatar asked Oct 22 '19 19:10

thatsme


People also ask

How to compare two ZonedDateTime?

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.

How do you subtract ZonedDateTime?

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.

What is ZonedDateTime in Java?

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.


2 Answers

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

like image 141
Joakim Danielson Avatar answered Nov 15 '22 09:11

Joakim Danielson


ZonedDateTime implements Comparable interface so you can simple use Collections.max

Collections.max(Arrays.asList(a,b));
like image 29
Deadpool Avatar answered Nov 15 '22 09:11

Deadpool