Test a deadline at the exact cutoff in Java

Inject a fixed clock so the result is reproducible. An exclusive deadline considers a request that arrives exactly at the cutoff late.

A simple example

Ask twice for the time

  1. Start with A fixed clock at noon
  2. Do this Ask twice for the time
  3. Result Noon both times
A fixed clock returns the chosen instant, making a boundary test repeatable.

Apply it to a real problem

  1. Start with An arrival at 11:59:59 or noon
  2. Do this Compare with a strict noon deadline
  3. Result On time, then late
Only arrivals strictly before the cutoff meet this rule.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.time.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Instant cutoff = Instant.parse("2024-04-01T12:00:00Z");
        for (Instant arrival : new Instant[]{cutoff.minusSeconds(1), cutoff}) {
            Clock clock = Clock.fixed(arrival, ZoneOffset.UTC);
            System.out.println(Instant.now(clock).isBefore(cutoff) ? "on time" : "late");
        }
    }
}
Output
on time
late

Official Java documentation