Search code examples
java-8java.time.instant

Check that Instant now happens during the java.time.Period / Duration


My intent is to set a condition to true only during a period.

The java.time.* API looked what I need.

import java.time.Period
import java.time.LocalTime
import java.time.Instant
import java.time.Duration

// java.time.Period
LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);
Period period = Period.between(startDate, endDate);

// java.time.duration
Instant start = Instant.parse("2017-10-03T10:15:30.00Z")
Instant end = Instant.parse("2019-10-03T10:16:30.00Z")
Duration duration = Duration.between(start, end)

Instant now = Instant.now();

How to check that now is happening during the defined Period / Duration ?

I see no direct API.

Edit : I found a way with java.time.Instant

// now, start and end are defined above
// if now is between start and end 
if (now.isAfter(start) && now.isBefore(end)){
}

Solution

  • You are mistaken about what Period and Duration are.

    They are distances (subtract beginning from ending). Period between 01/03/2018 and 01/10/2018 is exactly the same as in between 05/04/1990 and 05/11/1990, same thing for Duration. So that means nothing to ask something like "is 3rd january, 2018 in 3 months?"