Choosing Java time types and testing with Clock
Choose between Instant, local dates, offsets, and time zones, then inject a Java Clock to test coupon expiry boundaries without waiting.
I choose a Java time type by asking what the value represents. An event timestamp, a recurring appointment, and a coupon timeout carry different information and need different tests.
The examples use Java 21, Spring Boot 3.x, and JUnit 5. The
java.timeAPI was introduced in Java 8 through JSR 310.
Problems with Date, Calendar, and SimpleDateFormat
Date and Calendar are mutable. Returning one directly from an entity can let a caller change its state through a method such as setTime(). The older APIs can also obscure the representation. A Date describes a point on the timeline using epoch milliseconds and carries no zone. In new GregorianCalendar(2026, 11, 8), month 11 is December because the calendar uses zero-based month indexes.
SimpleDateFormat keeps mutable state and cannot be shared across threads without synchronization. A shared formatter can produce inconsistent results or throw while parsing under concurrency. An immutable DateTimeFormatter can be reused. It also makes the desired format and locale easier to identify in code.
Choosing a representation
The immutable types in java.time separate the timestamp, local calendar fields, offset, and geographical zone. A date-time that needs a zone rule should retain a ZoneId through the conversion that uses that rule.
flowchart TD
NEED["Choose a time representation"] --> POINT["Timestamp: Instant"]
NEED --> LOCAL["Calendar time: local types"]
NEED --> OFFSET["Known offset: OffsetDateTime"]
NEED --> ZONE["Regional rules: ZonedDateTime"]
NEED --> AMOUNT["Amount: Duration or Period"]
| Type | Information it carries | Example |
|---|---|---|
Instant | Seconds and nanoseconds on the timeline | Creation times, logs, or event timestamps |
LocalDate | A calendar date | A birthday or billing date |
LocalDateTime | Calendar date and wall-clock time | A local appointment with the zone tracked separately |
OffsetDateTime | Local date-time and an offset | API payloads containing an explicit UTC offset |
ZonedDateTime | Local date-time and geographic zone rules | An appointment set in a region with daylight saving |
Duration | Elapsed seconds and nanoseconds | Timeout, TTL, or execution time |
Period | Calendar years, months, and days | One calendar month until renewal |
A PostgreSQL TIMESTAMPTZ can preserve an instant. It does not preserve the original offset or zone designation. When a business rule needs the original zone, persist it separately. For display, project an instant into the viewer’s zone. If the wall-clock time is contractual, verify how the conversion handles a daylight-saving gap or overlap.
Moving the clock to the edge of the service
Direct calls to LocalDateTime.now() make a boundary test depend on the machine clock and its default zone. Inject a Clock so the service asks for time through one explicit dependency. In production it can read system time. In a test it returns a fixed instant and zone.
flowchart TD
SERVICE["CouponService"] --> CLOCK["Injected Clock"]
CLOCK --> PROD["System clock in production"]
CLOCK --> TEST["Fixed clock in tests"]
The Spring configuration supplies the clock. The coupon service uses it when deciding whether the expiration boundary has passed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/main/java/com/example/time/config/TimeConfig.java
package com.example.time.config;
import java.time.Clock;
import java.time.ZoneId;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.system(ZoneId.of("Asia/Seoul"));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/main/java/com/example/time/service/CouponService.java
package com.example.time.service;
import java.time.Clock;
import java.time.LocalDateTime;
import org.springframework.stereotype.Service;
@Service
public class CouponService {
private final Clock clock;
public CouponService(Clock clock) {
this.clock = clock;
}
public boolean isUsable(LocalDateTime expiredAt) {
LocalDateTime now = LocalDateTime.now(clock);
return !now.isAfter(expiredAt);
}
}
The business rule in the sample treats exactly the expiry time as valid. The choice of isAfter() makes that inclusivity explicit. If the business rule changes, update the decision and its boundary tests together.
Testing the expiry boundary with a fixed clock
The two tests construct the service directly, using Clock.fixed(). One sets the clock to the exact expiration instant. The other advances it beyond that instant. Neither depends on sleeping or on when the test process starts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/test/java/com/example/time/service/CouponServiceTest.java
package com.example.time.service;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class CouponServiceTest {
private static final ZoneId SEOUL = ZoneId.of("Asia/Seoul");
@Test
@DisplayName("A coupon is valid at its exact expiration time")
void usableAtExactExpirationTime() {
// 2026-11-08 23:59:59 KST (UTC+9 -> 14:59:59Z)
Clock fixedClock = Clock.fixed(Instant.parse("2026-11-08T14:59:59Z"), SEOUL);
CouponService couponService = new CouponService(fixedClock);
LocalDateTime expiredAt = LocalDateTime.of(2026, 11, 8, 23, 59, 59);
assertThat(couponService.isUsable(expiredAt)).isTrue();
}
@Test
@DisplayName("A coupon is invalid one second after expiration")
void expiredOneSecondAfterExpirationTime() {
// 2026-11-09 00:00:00 KST (UTC+9 -> 15:00:00Z)
Clock fixedClock = Clock.fixed(Instant.parse("2026-11-08T15:00:00Z"), SEOUL);
CouponService couponService = new CouponService(fixedClock);
LocalDateTime expiredAt = LocalDateTime.of(2026, 11, 8, 23, 59, 59);
assertThat(couponService.isUsable(expiredAt)).isFalse();
}
}
I start a time-sensitive test with the exact boundary, then cover just before and just after it. If the service consumes local input, I add dates on either side of a daylight-saving transition in the relevant region. Those tests help catch an accidental substitution of a fixed offset for the zone’s rules.