Close

Java Date Time - OffsetDateTime.until() Examples

Java Date Time Java Java API 


Class:

java.time.OffsetDateTime

java.lang.Objectjava.lang.Objectjava.time.OffsetDateTimejava.time.OffsetDateTimejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public long until(Temporal endExclusive,
                  TemporalUnit unit)
Returns the amount of time between this instance and the provided 'endExclusive' date-time in terms of the specified unit.

Examples


package com.logicbig.example.offsetdatetime;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;

public class UntilExample {

public static void main(String... args) {
OffsetDateTime d1 = OffsetDateTime.of(2014, 12, 15, 18,
29, 32, 3000000, ZoneOffset.ofHours(-5));
OffsetDateTime d2 = OffsetDateTime.of(2016, 12, 15, 18,
29, 32, 3000000, ZoneOffset.ofHours(-5));
System.out.printf("Original d1: %s%n", d1);
System.out.printf("Original d2: %s%n", d2);

for (ChronoUnit chronoUnit : ChronoUnit.values()) {
showUnit(d1, d2, chronoUnit);
}
}

private static void showUnit(OffsetDateTime d1, OffsetDateTime d2, ChronoUnit chronoUnit) {
try {
long until = d1.until(d2, chronoUnit);
System.out.printf("%s between d1 and d2: %s%n", chronoUnit.name(), until);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf("%s is not supported%n", chronoUnit);
}
}
}

Output

Original d1: 2014-12-15T18:29:32.003-05:00
Original d2: 2016-12-15T18:29:32.003-05:00
NANOS between d1 and d2: 63158400000000000
MICROS between d1 and d2: 63158400000000
MILLIS between d1 and d2: 63158400000
SECONDS between d1 and d2: 63158400
MINUTES between d1 and d2: 1052640
HOURS between d1 and d2: 17544
HALF_DAYS between d1 and d2: 1462
DAYS between d1 and d2: 731
WEEKS between d1 and d2: 104
MONTHS between d1 and d2: 24
YEARS between d1 and d2: 2
DECADES between d1 and d2: 0
CENTURIES between d1 and d2: 0
MILLENNIA between d1 and d2: 0
ERAS between d1 and d2: 0
Forever is not supported




See Also