SteelReed

Search

Search posts, questions…

3. Advanced Java

Storing dates and times in PostgreSQL, MySQL and JSON: timestamptz, DATETIME, Jackson and the traps

Timestamps vs datetimes, PostgreSQL timestamptz vs timestamp, MySQL TIMESTAMP vs DATETIME (the 2038 limit, session conversion), rounded fractional seconds, why future appointments need a zone id, JDBC/Hibernate/Connector/J, and JSON traps: Jackson, ISO 8601, epoch numbers and JavaScript Date.

18 Nov 20267 min readMid

–

1. The problem

The "June 10" report run from the app (JVM in UTC) and from DBeaver on a laptop (Vietnam time) gives two totals, because created_at::date follows the session time zone.

2. Key idea

The DB, driver, ORM, JSON and frontend each read time their own way. First, separate two kinds of data:

  • Instant: a point on the timeline, the same everywhere (created_at, paid_at). Like lightning, everyone sees it at once.
  • Wall-clock time: a time on a calendar tied to a place ("meeting at 9:00 in Paris", a birthday). It only means something with that place's time rules.
Data PostgreSQL MySQL Java
Instant timestamptz DATETIME(6) in UTC Instant
Calendar date (birthday) date DATE LocalDate
Time of day (opening hours) time TIME LocalTime
Future appointment timestamp + zone id text DATETIME + VARCHAR LocalDateTime + ZoneId

2.1 Which column does what?

Type Use when Don't use when
PostgreSQL timestamptz every *_at column; stores UTC, displays per session pure wall-clock time (the time printed on a train ticket)
PostgreSQL timestamp wall-clock time with a zone id column beside it instants: the offset is dropped, data gets mixed
MySQL DATETIME(6) UTC instants in new systems; driver forces UTC without (6): microseconds lost
MySQL TIMESTAMP values near now, with a plan before 2038 long-lived contracts; services with different time_zone

2.2 Three common traps

  • Filtering by day: WHERE created_at::date = '2024-06-10' depends on the session and skips the index. Use a half-open range with an offset: created_at >= '2024-06-10T00:00+07:00' AND created_at < '2024-06-11T00:00+07:00'.
  • Rounding: PostgreSQL keeps microseconds; MySQL defaults to 0 fractional digits and rounds (.6 becomes the next second). Instant.now() can carry nanoseconds.
  • Future appointments: 9:00 in Paris in 2027 stored as an Instant now is wrong if France drops summer time before then. Store wall-clock time + zone id; an Instant column is only precomputed for indexing.

3. In Java

JAVA
// Every layer speaks UTC: JVM, hibernate.jdbc.time_zone=UTC, Connector/J connectionTimeZone=UTC
Instant createdAt = Instant.now(clock).truncatedTo(ChronoUnit.MICROS);  // matches timestamptz, DATETIME(6)
 
ps.setObject(1, createdAt.atOffset(ZoneOffset.UTC));                    // JDBC 4.2 doesn't require Instant
Instant read = rs.getObject("created_at", OffsetDateTime.class).toInstant();
 
record Appointment(LocalDateTime localStart, ZoneId zone) {
    Instant startInstant() { return localStart.atZone(zone).toInstant(); }
}
// new Appointment(LocalDateTime.of(2027, 7, 1, 9, 0), ZoneId.of("Europe/Paris")).startInstant()
// 2027-07-01T07:00:00Z (per current tzdata)
 
new ObjectMapper();   // hand-made: Instant throws InvalidDefinitionException; + JavaTimeModule still gives numbers

Spring Boot's ObjectMapper is already configured: "createdAt":"2023-09-25T09:20:52.342Z".

JSON sends instants as RFC 3339 with Z and calendar dates as "2023-10-01". JavaScript's new Date("2023-09-25") means UTC midnight, which is the 24th in the US.

PostgreSQL and MySQL: session time zone, AT TIME ZONE, 2038
  • The session TimeZone decides which local date a timestamptz becomes; with PgJDBC it's the JVM's default time zone.
  • AT TIME ZONE '+07:00' in PostgreSQL means UTC−7 (POSIX convention); in MySQL '+07:00' is UTC+7. Use IANA zone names. Group by day with date_trunc('day', created_at, 'Asia/Ho_Chi_Minh').
  • Converting an old timestamp column to timestamptz: USING created_at AT TIME ZONE 'Asia/Ho_Chi_Minh' states what the old data was; on big tables use expand/contract, since the command rewrites the table under a lock.
  • MySQL TIMESTAMP ends at 2038-01-19 03:14:07 UTC; writing past it gives ERROR 1292. CONVERT_TZ with zone names silently returns NULL if the time zone tables aren't loaded.
  • Jackson by default shifts an OffsetDateTime's offset to UTC when reading (ADJUST_DATES_TO_CONTEXT_TIME_ZONE); if the offset matters to the business, turn it off or store a zone id separately.

4. Working with AI

Delegate to AI: column-type migrations, save-and-read tests, Jackson and driver configuration.

Check yourself:

  • Instant columns are timestamptz or DATETIME(6), not bare timestamp or DATETIME.
  • No java.sql.Timestamp, no hand-made new ObjectMapper() missing JavaTimeModule.
  • Day filters use half-open ranges with offsets, not ::date or DATE(col).
  • Future schedules have a zone id column; zones are IANA names, not offsets.

5. Exercises

Exercise 1: A "save then read back" test fails at random

An integration test saves Instant createdAt = Instant.now() to MySQL, reads it back and assertEquals. Green on a dev machine, red 1 in 5 on CI. AI suggests "add a retry to the test". Diagnose and fix.

Solution to Exercise 1
  • The column is DATETIME or DATETIME(3) while Instant.now() has microseconds; MySQL rounds, so the value read back differs, sometimes by a whole second. "Sometimes" because it depends on the random fraction. A retry just hides it.
  • Fix: a DATETIME(6) column, truncatedTo(ChronoUnit.MICROS) before saving, Clock.fixed in tests.
  • The same bug breaks optimistic locking on updated_at and time-based pagination cursors, not just tests.

Exercise 2: Pick column types

Choose PostgreSQL types for: (a) order creation time, (b) birthday, (c) a doctor's appointment in Singapore next year, (d) the expiry date of a 30-year contract (and on MySQL?).

Solution to Exercise 2
  • (a) timestamptz: an instant.
  • (b) date: a calendar date, not an instant.
  • (c) timestamp + time_zone text (Asia/Singapore), plus a precomputed start_at timestamptz if you need an index.
  • (d) date. On MySQL use DATE or DATETIME(6), not TIMESTAMP, since it passes 2038.

Summary

  • Instants stored in UTC (timestamptz, DATETIME(6)); future wall-clock times with a zone id.
  • timestamptz doesn't store a time zone; timestamp drops the offset.
  • MySQL TIMESTAMP expires in 2038 and converts per session.
  • Databases round fractional seconds: truncate before writing.
  • JSON: RFC 3339 with Z; use Spring's ObjectMapper.

Back to: Part 1: Epoch, time zones and java.time.

Practice interview questions on this topic

All Data Modeling & Scaling questions →

Loading comments…
Next on the roadmapInside the JVM: runtime memory areas, class loading and ClassLoaders