Java 8: Calculate difference between two ZonedDateTime

Maggie Hill picture Maggie Hill · Dec 10, 2016 · Viewed 47.1k times · Source

I'm trying to write a method to print the time difference between two ZonedDateTimes, regarding the difference between time zones.

I found some solutions but all of them were written to work with LocalDateTime.

Answer

Michał Szewczyk picture Michał Szewczyk · Dec 10, 2016

You can use method between from ChronoUnit.

This method converts those times to same zone (zone from the first argument) and after that, invokes until method declared in Temporal interface:

static long zonedDateTimeDifference(ZonedDateTime d1, ZonedDateTime d2, ChronoUnit unit){
    return unit.between(d1, d2);
}

Since both ZonedDateTime and LocalDateTime implements Temporal interface, you can write also universal method for those date-time types:

static long dateTimeDifference(Temporal d1, Temporal d2, ChronoUnit unit){
    return unit.between(d1, d2);
}

But keep in mind, that invoking this method for mixed LocalDateTime and ZonedDateTime leads to DateTimeException.

Hope it helps.