1

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)){
}
Raymond Chenon
  • 11,482
  • 15
  • 77
  • 110

2 Answers2

2

First: a simple solution:

LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);
LocalTime now = LocalTime.now()

boolean nowIsInTimeWindow = !(now.isBefore(start) || now.isAfter(end));

The same pattern works with LocalDate and LocalDateTime.

Second: additional thoughts on your original post:

  1. now will never happen "during" period or duration. Both are just amounts of time, like "two days" or "five minutes". They don't contain information about start or end.

  2. I'd suggest to not mix Instant and LocalDate but to use LocalTime instead of Instant. Thus you're consistent with regard to timezone: The Local... types are by definition timezone agnostic.

Amadán
  • 718
  • 5
  • 18
  • 1
    you took the solution I gave in my "edit" :) It looks strange that `Period/Duration` don't have an API to check that an `Instant` is in their time window – Raymond Chenon May 31 '18 at 13:13
  • 2
    You were just too quick finding out while I still wrote an anser. ;-) Still: refrain from mixing LocalTime and Instant easily! LocalTime.now() may differ depending on your location on earth. Instant.now() should be the same in all places. Doesn't look strange to me. Both classes are NOT about time windows, but only measuring time passing. Imagine asking: "When did five hours and six minutes start?" That does not make sense. – Amadán May 31 '18 at 13:17
2

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?"

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69