Video in progress
A Java service in a container writes times off by 5 hours. What is the cause, and how should it be set up properly?
A container image is usually in UTC, and the JVM takes its default timezone from the OS. If the code uses LocalDateTime.now() without a zone, the result depends on the environment. The right way is Instant/UTC for storage and exchange, and an explicit ZoneId in business rules.
📖 Answer
Tashkent is UTC+5. On a laptop everything is right, but in prod the "today's orders" report also includes yesterday's. That is because the container has no TZ, and the JVM took UTC as the default.
The quick patch is to fix the environment:
env:
- name: TZ
value: Asia/Tashkent
# or a JVM flag: -Duser.timezone=Asia/Tashkent
This works, but it hides the problem: the code still depends on the environment, and tomorrow another service or a test runner will be in UTC. The reliable way is in the code:
// for storage and between services: a point in time
Instant createdAt = Instant.now(clock);
// if the business rule is "today in Tashkent", state the zone explicitly
ZoneId tashkent = ZoneId.of("Asia/Tashkent");
LocalDate today = LocalDate.now(clock.withZone(tashkent));
If you inject Clock as a bean, it is also easy to freeze time in tests.
On the DB side: use timestamptz in Postgres. In Hibernate 6, hibernate.jdbc.time_zone=UTC brings the times sent over JDBC into one zone. @Scheduled(cron = "0 0 2 * * *") also runs in the JVM's default zone, so add zone = "Asia/Tashkent" if you need it.
The same question applies to logs: if every service writes in UTC, comparing the logs of several services during an incident is easy. When showing a time to a user, you convert it to their zone.
Sign up to mark studied questions and save your progress.