On JDK 23 with pgjdbc 42.7.10, .123456789 came back as .123457 and equals failed. Truncate to microseconds where time enters the system and test with a fixed Clock.
A test that passed on one machine and failed on another
At Belgavi's Book Store, the returns service records when each return was received. A repository test saves a Return with receivedAt = Instant.now(), reads it back, and asserts the two objects are equal. It passed on one developer's machine and failed on the build server, and on a second laptop it failed about half the time. The database column is PostgreSQL timestamptz; the driver is pgjdbc.
The cause is precision. Instant can hold nanoseconds, timestamptz stores microseconds, and something has to decide what happens to the last three digits. This guide measures what the clock, the driver and the server each do on JDK 23.0.2, pgjdbc 42.7.10 and PostgreSQL 18.4, then fixes it at the boundary where values enter the system.
Three components, three precisions
| Component | Precision | Documented behaviour |
|---|---|---|
java.time.Instant | nanoseconds | getNano() returns 0 to 999,999,999 |
Clock.systemUTC() / Instant.now() | platform dependent | the Javadoc says it uses the best available system clock, which may be System.currentTimeMillis() or a higher resolution clock if one is available |
PostgreSQL timestamp and timestamptz | 1 microsecond | the documentation gives a resolution of 1 microsecond |
The clock's precision has changed over JDK releases and differs by operating system. JDK 8's system clock returned whole milliseconds. JDK 9 raised the precision of Clock.systemUTC() (JDK-8068730), and JDK 15 enhanced the system clock to nanosecond precision (JDK-8242504). That history is why tests written for JDK 8, when Instant.now() always had zeros after the third decimal, started failing after an upgrade.
What I measured
The companion probe took 20,000 Instant.now() samples on Windows 11 and wrote five fixed instants through pgjdbc into a timestamptz column, reading each back with getObject(..., OffsetDateTime.class).
On this machine, 19,487 of the 20,000 samples had non-zero digits below the microsecond, yet the smallest step between consecutive distinct samples was 0.997 ms. The values carried 100-nanosecond digits, but the clock advanced about once per millisecond. A test that happens to sample a value with zeros in the last three digits passes; most do not.
| Written | Read back | equals written |
|---|---|---|
.123456789 via setObject(OffsetDateTime) | .123457 | false |
.123456789 via setTimestamp | .123457 | false |
.123456499 via either | .123456 | false |
.999999700 via either | the next whole second | false |
.123456000 via either | .123456 | true |
| any value truncated to microseconds first | the truncated value | true |
The driver rounds rather than truncates. pgjdbc's TimestampUtils adds a microsecond when the nanoseconds within a microsecond exceed 499, and wraps into the next second at .9999995. So .123456789 becomes .123457, not .123456, and Instant.truncatedTo(ChronoUnit.MICROS) on the original would not match either. A SQL literal parsed by the server, '2026-11-08 09:15:30.1234565+00', came back as .123456, so the server and the driver do not even agree on halves. That disagreement is the reason to stop sending nanoseconds at all.
The fix: choose the stored precision before writing
Truncate once, at the point where a time enters your domain, and keep only the truncated value:
public final class Times {
private final Clock clock;
public Times(Clock clock) { this.clock = clock; }
/** Now, at the precision the database stores. Use this instead of Instant.now(). */
public Instant now() {
return Instant.now(clock).truncatedTo(ChronoUnit.MICROS);
}
}With this, the value in memory, the value in the database and the value read back are the same Instant, and equals works. The probe's last rows show it: a truncated value round-trips unchanged through both driver paths. Truncate rather than round, because truncation can never carry into the next second or the next day, which matters for values used as partition keys or in date-based reports.
Inject the Clock. Tests then use Clock.fixed(Instant.parse("2026-11-08T09:15:30.123456Z"), ZoneOffset.UTC), which removes the platform dependence entirely and makes "now" a value the test controls.
Clock fixed = Clock.fixed(Instant.parse("2026-11-08T09:15:30.123456Z"), ZoneOffset.UTC);
Times times = new Times(fixed);
Return r = new Return("CASE-4127", times.now());
repo.save(r);
assertEquals(r, repo.find("CASE-4127"));When you cannot change the writer
If values arrive from elsewhere with full precision, compare at a declared precision rather than with equals:
static boolean sameMicros(Instant a, Instant b) {
return Math.abs(Duration.between(a, b).toNanos()) < 1_000;
}A tolerance of under a microsecond accepts both rounding and truncation. If your tests use AssertJ, its isCloseTo(expected, within(1, ChronoUnit.MICROS)) assertion on instants expresses the same intent and prints both values when it fails, which makes a precision mismatch obvious in the build log. Use it in tests and in reconciliation code, never in a primary key. For keys, convert to the stored precision before the value becomes a key, or use an identifier that is not a time.
Boundaries in queries, not only in equals
The same rounding affects range conditions. A report of returns received before a cut-off runs WHERE received_at < ? with the cut-off as an Instant. If both the stored values and the parameter pass through the driver, both are rounded the same way and the comparison is consistent. If the cut-off was computed in Java from a value read back earlier and then adjusted by nanoseconds, or if one side came from a SQL literal parsed by the server, a row at the boundary can fall on either side. Half-open ranges on values already at the stored precision avoid the question: compute the bounds, truncate them to microseconds, then query received_at >= :start AND received_at < :end.
Migrating an existing codebase
- Replace direct calls to
Instant.now(),LocalDateTime.now()andOffsetDateTime.now()in domain code with an injected clock wrapper such asTimesabove. A search for.now(finds them. - Truncate in one place: the wrapper for values the application creates, and the mapping layer for values that arrive from other systems.
- Keep the database column at microsecond precision. If an ORM generated
timestamp(3)or similar, the stored precision is milliseconds and the wrapper must truncate to milliseconds to match. - Add one repository test with a value that has nanoseconds set, and one that uses
Clock.fixed. - Log instants with the same precision you store, so that log lines and database rows can be matched by value.
Other databases do it differently
The fix does not depend on the database, but the failure does. MySQL's DATETIME and TIMESTAMP columns default to whole seconds unless declared with a fractional precision such as DATETIME(6), and MySQL documents that inserting a value with more fractional digits than the column holds rounds it, unless the TIME_TRUNCATE_FRACTIONAL SQL mode is enabled. Other drivers may truncate where pgjdbc rounds. Measure the driver and server pair you actually run, with the probe or something like it, rather than assuming.
Where this shows up besides tests
- Optimistic locking on a timestamp. A
WHERE updated_at = :read_valueupdate compares the rounded stored value with the unrounded value in memory and matches nothing. Use a version number instead. - Cache keys and deduplication. A key built from an
Instantbefore saving differs from the same key built after reading. - Event ordering. Two events a few hundred nanoseconds apart round to the same microsecond and lose their order. Add a sequence number.
- Cross-service comparisons. A service on Linux and one on Windows produce instants with different digits for the same moment; compare at the stored precision.
Verifying it
The companion RoundingCheck.java runs without a database and asserts the rounding rule, the carry into the next second, and that truncate-first values survive. InstantRoundTrip.java runs the table above against your own driver and server, and run.sh compares the result with the recording. Add a repository test that saves and reloads a value with nanoseconds set, such as .123456789, because a value read from a millisecond clock will hide the problem on the machine where you write the test.