Skip to content

Clock & Time Support

The RuleContext includes a Clock for time-based operations. By default it uses Clock.systemDefaultZone(), but you can inject a fixed clock for deterministic, reproducible test results.

// Default clock (system time)
RuleContext ctx = RuleContext.builder().build(bindings);
Clock clock = ctx.getClock(); // System default zone
// Fixed clock for testing
Clock fixedClock = Clock.fixed(
Instant.parse("2025-06-15T12:00:00Z"),
ZoneId.of("UTC"));
RuleContext testCtx = RuleContext.builder()
.clock(fixedClock)
.build(bindings);

rulii provides built-in validation rules that use the context clock to evaluate temporal values:

Rule Description
PastValidationRule Value must be in the past
PastOrPresentValidationRule Value must be in the past or present
FutureValidationRule Value must be in the future
FutureOrPresentValidationRule Value must be in the future or present

(new in 2.2.0) Besides the ISO types, these rules and TimeComparator accept the java.time.chrono dates HijrahDate, JapaneseDate, MinguoDate and ThaiBuddhistDate, compared with the date of the configured clock in their own calendar — completing Bean Validation’s list of temporal types.

// Validate a date is in the future
Rule futureCheck = Rule.builder()
.build(new FutureValidationRule("eventDate"));
RuleViolations violations = new RuleViolations();
futureCheck.run(
eventDate -> LocalDate.of(2020, 1, 1),
ruleViolations -> violations
);
violations.hasErrors(); // true — 2020 is in the past

Inject a fixed clock so that “now” is a known, deterministic value. This makes temporal validation rules fully testable:

Clock fixedClock = Clock.fixed(
Instant.parse("2025-01-01T00:00:00Z"), ZoneId.of("UTC"));
RuleContext ctx = RuleContext.builder()
.clock(fixedClock)
.build(eventDate -> LocalDate.of(2025, 6, 15),
ruleViolations -> new RuleViolations());
// Now "future" is relative to 2025-01-01, not actual current time

The RuleContext also tracks when it was created. This can be useful for logging and auditing:

RuleContext ctx = RuleContext.builder().build(bindings);
ctx.getCreationTime(); // Instant when the context was created
  • Deterministic Testing Fixed clocks ensure tests are not affected by wall-clock time
  • Timezone-Aware Validation Use specific ZoneIds for timezone-sensitive rule evaluation