Java 8: Calculate difference between two ZonedDateTime

后端 未结 2 1426
北荒
北荒 2020-12-03 00:14

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

I found some sol

2条回答
  •  鱼传尺愫
    2020-12-03 00:49

    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.

提交回复
热议问题