BackendBench
Coffee
Spot the Bug #75

A timestamp without a zone

A medium Java puzzle in the dates, time zones and dst family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumDates, time zones and DSTbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

LocalDateTime has no zone or offset, so the stored value means different instants on servers in different zones and cannot be ordered across them. Audit logs need an unambiguous point in time.

The fix

return new Entry(action, Instant.now()); // store Instant or OffsetDateTime in UTC

How to avoid it next time

Store instants (Instant, or timestamptz in the database) and convert to a zone only for display.

Want the background? Read Time zones, DST and Instant in the Java concepts library.

About dates, time zones and dst

Local dates and times hide the zone they belong to. Daylight saving changes the length of a day, a month has varying lengths and the week-year differs from the calendar year around New Year.

In code review: Ask which zone each date is in and whether the code uses an instant or a local time. Prefer java.time with an explicit ZoneId over Date and SimpleDateFormat.

More puzzles in this family

🐞 Play today's puzzleAll 132 bugs← #74#76 →

Frequently asked questions

What is the bug in "A timestamp without a zone"?

LocalDateTime has no zone or offset, so the stored value means different instants on servers in different zones and cannot be ordered across them. Audit logs need an unambiguous point in time. The faulty line is line 7: return new Entry(action, LocalDateTime.now());

How do I fix it?

Replace it with: return new Entry(action, Instant.now()); // store Instant or OffsetDateTime in UTC. Store instants (Instant, or timestamptz in the database) and convert to a zone only for display.

How do I catch dates, time zones and dst in code review?

Ask which zone each date is in and whether the code uses an instant or a local time. Prefer java.time with an explicit ZoneId over Date and SimpleDateFormat.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need