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
Section titled “Default and Fixed Clocks”// Default clock (system time)RuleContext ctx = RuleContext.builder().build(bindings);Clock clock = ctx.getClock(); // System default zone
// Fixed clock for testingClock 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
Section titled “Built-in Temporal Validation Rules”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.
Example: Future Date Validation
Section titled “Example: Future Date Validation”// Validate a date is in the futureRule 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 pastTesting with a Fixed Clock
Section titled “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 timeCreation Time
Section titled “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 createdUse Cases
Section titled “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