Dates and times in the backend: epoch, UTC, time zones, ISO 8601 and java.time
How computers store time (epoch seconds vs milliseconds, Y2038), how UTC differs from GMT, ISO 8601 / RFC 3339 / RFC 1123, why you need IANA zone ids rather than fixed offsets (DST), choosing the right java.time type, the JVM time zone, and a case study of a booking service getting 'today' and the number of nights wrong.
On this page
1. The problem
The server runs in UTC, the homestay is in Da Nang. At 6:30 a.m. on December 24 Vietnam time, LocalDate.now() on the server is still December 23, so the API accepts a December 23 check-in: a night already gone, sold anyway. The same week, a JWT with exp = System.currentTimeMillis() + 3600_000 "expires" tens of thousands of years later, because exp is in seconds.
2. Key idea
Computers store time as seconds (or milliseconds) since 1970-01-01T00:00:00Z, the same everywhere. A time zone is just how each place reads that number. An offset (+01:00) is the difference at one instant; an IANA zone id (Europe/Paris) is the rule, including daylight saving: Paris is +01:00 in winter and +02:00 in summer. Abbreviations (CST, IST) are ambiguous; don't store them.
java.time type |
Meaning | Example data |
|---|---|---|
Instant |
a point on the timeline (UTC) | created_at, payments, logs |
OffsetDateTime |
Instant + offset | APIs sending offsets, JDBC for timestamptz |
LocalDate |
a calendar date | birthdays, check-in |
LocalDateTime + ZoneId |
wall-clock time in a region | future appointments |
Duration / Period |
elapsed time / calendar span | 30-second timeout / extend by 1 month |
2.1 How do you add a day?
| Approach | Use when | Don't use when |
|---|---|---|
plusDays(1), Period |
appointments, reminders, "expires end of tomorrow" | TTLs, timeouts |
plus(Duration.ofHours(24)) |
TTLs, 24-hour tokens, rate limits | wall-clock time must hold across DST |
JSON APIs use RFC 3339 (2023-09-25T09:20:52.342Z); local display formats are for display only.
3. In Java
ZoneId paris = ZoneId.of("Europe/Paris");
ZonedDateTime before = ZonedDateTime.of(LocalDateTime.of(2024, 3, 30, 9, 0), paris);
before.plusDays(1); // 2024-03-31T09:00+02:00[Europe/Paris]
before.plus(Duration.ofHours(24)); // 2024-03-31T10:00+02:00[Europe/Paris]
Instant.ofEpochSecond(1695718262342L); // +55705-03-04T18:39:02Z (ms read as seconds)
// The homestay's "today", not the server's; an injected Clock makes edge times testable
LocalDate today = LocalDate.now(clock.withZone(homestay.zone()));
long nights = ChronoUnit.DAYS.between(checkIn, checkOut); // LocalDate: unaffected by DST
ZoneId.of("Asia/Hanoi"); // ZoneRulesException: bad id, fails fast
TimeZone.getTimeZone("Asia/Hanoi"); // silently returns GMT
DateTimeFormatter.ofPattern("YYYY-MM-dd").format(LocalDate.of(2024, 12, 30)); // 2025-12-30YYYY is the week-based year; use yyyy or ISO_OFFSET_DATE_TIME. Other languages: JavaScript's Date.now() is milliseconds, Python's time.time() is seconds; Go has time.LoadLocation("Europe/Paris").
Gaps, overlaps, Y2038 and the JVM time zone
- Gap: 02:30 on March 31, 2024 in Paris doesn't exist;
ZonedDateTime.ofmoves it to 03:30. Overlap: 02:30 on October 27, 2024 happens twice; choose withwithEarlierOffsetAtOverlap()orwithLaterOffsetAtOverlap(). - Y2038: signed 32-bit epoch seconds overflow at 2038-01-19T03:14:07Z.
INTcolumns holding epochs, and MySQLTIMESTAMP, share this limit. OffsetDateTime.equalscompares offsets too; compare instants withisEqual.- The JVM's default zone comes from
-Duser.timezone, theTZvariable or the OS. Set UTC for the JVM, DB sessions and containers, then pass an explicitZoneIdto every calendar computation. - Governments change time zone rules; update the JDK (tzdata) regularly.
4. Working with AI
Hand to AI: tests across the DST switches of Europe/Paris and America/Los_Angeles, a table mapping fields to java.time types, normalizing incoming epochs.
Check yourself in AI-written code:
- No argument-less
LocalDate.now()orLocalDateTime.now(); aClockis injected. - Epoch fields carry their unit in the name (
expiresAtEpochSeconds,createdAtMs) or useInstant. - IANA zone ids are stored, never fixed offsets or abbreviations.
- TTLs use
Duration; appointments usePeriod/plusDays. - Format patterns use
yyyy,dd, notYYYY,DD.
5. Exercises
Exercise 1: Convert Hanoi time to Paris and California
Given 2023-09-26T07:15:52+07:00, the AI writes instant.atOffset(ZoneOffset.ofHours(1)) for Paris and ofHours(-8) for California. Are the results right? Fix it.
Solution 1
Off by an hour: in late September, Paris and California are on summer time. Use zone ids:
Instant instant = OffsetDateTime.parse("2023-09-26T07:15:52+07:00").toInstant();
instant.atZone(ZoneId.of("Europe/Paris")).toOffsetDateTime(); // 2023-09-26T02:15:52+02:00
instant.atZone(ZoneId.of("America/Los_Angeles")).toOffsetDateTime(); // 2023-09-25T17:15:52-07:00California is still on the previous day. An offset is the result of a rule at an instant, not a fixed property of a city.
Exercise 2: Review a check-in validation
The AI wrote the code below for a homestay in Da Nang and says "tested". The server runs in UTC. Find two bugs, name tests that prove them, fix it.
if (req.checkIn().isBefore(LocalDate.now())) throw new InvalidDatesException();
long nights = Duration.between(req.checkIn().atStartOfDay(), req.checkOut().atStartOfDay()).toHours() / 24;Solution 2
LocalDate.now()uses the server's date (UTC): from midnight to 7 a.m. Vietnam time, the server's "today" is still yesterday, so past check-in dates get accepted; in zones behind UTC it's the reverse, and today gets rejected. Fix:LocalDate.now(clock.withZone(homestay.zone())).- Counting nights through
Durationand hours: for a homestay in a DST zone, a 23-hour day makes/ 24lose a night. Fix:ChronoUnit.DAYS.between(checkIn, checkOut)onLocalDate. - Tests:
Clock.fixed(Instant.parse("2026-12-23T23:30:00Z"), UTC)(6:30 a.m. Dec 24 in Vietnam) must reject a Dec 23 check-in and accept Dec 24; aEurope/Parishomestay from March 30 to April 1 must give 2 nights.
Summary
- Epochs have no time zone; state seconds or milliseconds.
- Store IANA zone ids; an offset is only right at one instant.
- With DST a day is 23 or 25 hours:
Periodfor calendars,Durationfor TTLs. - Pick types by meaning:
Instant,LocalDate, local time +ZoneId. - Servers run UTC; compute "today" in the business
ZoneIdvia an injectedClock.
Further reading: Storing dates in the database and JSON.
Practice interview questions on this topic
- Why did java.time replace Date and Calendar? How do you use LocalDate, LocalDateTime and Instant?
- Does a Unix timestamp depend on the time zone? When do you use Instant and when LocalDate?
- How does an offset differ from a ZoneId? Why is plusDays(1) different from adding 24 hours?
- What time conventions would you set for a multi-service system?
Comments
Community rules