Java Reference
In-Depth Information
Start Datetime: 2012-03-10T07:30-06:00[America/Chicago]
After 1 Day period: 2012-03-11T07:30-05:00[America/Chicago]
After 24 Hours duration: 2012-03-11T08:30-05:00[America/Chicago]
Period Between Two Dates and Times
It is a common requirement to compute the amount of time elapsed between two dates, times, and datetimes. For
example, you may need to compute the number of days between two local dates or the number of hours between two
local datetimes. The Date-Time API provides methods to compute the elapsed period between two dates and times.
There are two ways to get the amount of time between two dates and times.
•
Use the
between()
method on one of the constants in the
ChronoUnit
enum.
until()
method on one of the datetime-related classes, for example,
LocalDate
,
LocalTime
,
LocalDateTime
,
ZonedDateTime
, etc.
The
ChronoUnit
enum has a
between()
method, which takes two datetime objects and returns a
long
. The
method returns the amount of time elapsed from the first argument to the second argument. If the second argument
occurs before the first one, it returns a negative amount. The returned amount is the complete number of units
between two dates and times. For example, if you call
HOURS.between(lt1, lt2)
, where
lt1
and
lt2
are 07:00 and
09:30 respectively, it will return 2, not 2.5. However, if you call
MINUTES.between(lt1, lt2)
, it will return 150.
The
untll()
method takes two parameters. The first parameter is the end date or time. The second parameter is
the time unit in which to compute the elapsed time. The program in Listing 12-12 shows how to use both methods to
compute the amount of time between two dates and times.
•
Use the
Listing 12-12.
Computing the Amount of Time Elapsed Between Two Dates and Times
// TimeBetween.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
public class TimeBetween {
public static void main(String[] args) {
LocalDate ld1 = LocalDate.of(2014, Month.JANUARY, 7);
LocalDate ld2 = LocalDate.of(2014, Month.MAY, 18);
long days = DAYS.between(ld1, ld2);
LocalTime lt1 = LocalTime.of(7, 0);
LocalTime lt2 = LocalTime.of(9, 30);
long hours = HOURS.between(lt1, lt2);
long minutes = MINUTES.between(lt1, lt2);
System.out.println("Using between (days): " + days);
System.out.println("Using between (hours): " + hours);
System.out.println("Using between (minutes): " + minutes);