24 — Advanced

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 and Fixed Clocks

// 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);

Built-in Temporal Validation Rules

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

Rule Description
PastValidationRuleValue must be in the past
PastOrPresentValidationRuleValue must be in the past or present
FutureValidationRuleValue must be in the future
FutureOrPresentValidationRuleValue must be in the future or present

Example: Future Date Validation

// 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

Testing with a Fixed Clock

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

Creation 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

Use Cases

Deterministic Testing

Fixed clocks ensure tests are not affected by wall-clock time

Timezone-Aware Validation

Use specific ZoneIds for timezone-sensitive rule evaluation