Home Ask Login Register

Developers Planet

Your answer is one click away!

Dmitrii Adonin February 2016

Temporal calculations with Java 8 java.time.*

Let us have java.time.Instant - start point of some event, and java.time.Duration - duration of this event.

Can I use java.time.Period to calculate if another Instant belongs to this period? If no - which approach should I use to define it?


Tunaki February 2016

Given the instant instant and the duration duration, you want to check if the instant toCheck belongs to the interval [instant; instant + duration].

For this, you can calculate the duration between instant and toCheck with Duration.between. If this duration is positive and it is less than the specified duration then the instant to check is in the wanted interval.

public static void main(String[] args) {
    Instant instant = Instant.now();
    Duration duration = Duration.ofSeconds(10);
    Instant toCheck = instant.plusSeconds(5);

    Duration d = Duration.between(instant, toCheck);
    if (!d.isNegative() && d.compareTo(duration) <= 0) {
        System.out.println("is in interval!");

wero February 2016

Another solution based on a start and end Instant for a more intuitive comparison:

    Instant start     = Instant.now(); // your value
    Duration duration = Duration.ofSeconds(10);  // your value
    Instant end       = start.plus(duration);

    Instant toCheck   = start.plusSeconds(5); // your value
    if (!toCheck.isBefore(start) && !toCheck.isAfter(end)) 
        System.out.println("is in interval!");

jbx February 2016

A somewhat more contorted example using Period as requested by the OP. This is more useful if you want to use Days, Weeks, Months etc. between your Instants and want to make sure daylight saving, leap years etc. are taken care of seamlessly.

Instant start = Instant.now();
ZonedDateTime eventStart = ZonedDateTime.ofInstant(start, ZoneId.systemDefault());
ZonedDateTime eventEnd = eventStart.plus(Period.ofDays(5));
Instant end = eventEnd.toInstant();

Instant toCheck = start.plus(2, ChronoUnit.DAYS);

if (!toCheck.isBefore(start) && !toCheck.isAfter(end))
  System.out.println("Instant to check is between start and end");

JodaStephen February 2016

The ThreeTen-Extra project includes java.time features that didn't make the cut for the JDK. One of these is Interval, see the Javadoc.

Using Interval, this problem can be written as:

Interval iv = Interval.of(start, duration);
boolean contains = iv.contains(instantToCheck);

Post Status

Asked in February 2016
Viewed 3,723 times
Voted 5
Answered 4 times


Leave an answer

Quote of the day: live life