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.
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.
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:
Since both ZonedDateTime and LocalDateTime implements Temporal interface, you can write also universal method for those date-time types:
But keep in mind, that invoking this method for mixed LocalDateTime and ZonedDateTime leads to DateTimeException.
Hope it helps.
tl;dr
For hours, minutes, seconds:
For years, months, days:
Details
The Answer by Michal S is correct, showing
ChronoUnit
.Duration
&Period
Another route is the
Duration
andPeriod
classes. Use the first for shorter spans of time (hours, minutes, seconds), the second for longer (years, months, days).Produce a String in standard ISO 8601 format by calling
toString
. The format isPnYnMnDTnHnMnS
where theP
marks the beginning andT
separates the two portions.In Java 9 and later, call the
to…Part
methods to get the individual components. Discussed in another Answer of mine.Example code
See live code in IdeOne.com.
Interval
&LocalDateRange
The ThreeTen-Extra project adds functionality to the java.time classes. One of its handy classes is
Interval
to represent a span of time as a pair of points on the timeline. Another isLocalDateRange
, for a pair ofLocalDate
objects. In contrast, thePeriod
&Duration
classes each represent a span of time as not attached to the timeline.The factory method for
Interval
takes a pair ofInstant
objects.You can obtain a
Duration
from anInterval
.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.