How to Properly Handle Time Zones in Web Applications
Any web page that displays time needs to deal with time zones, because users can be located anywhere in the world. You don’t want user at 10:00 a.m. seeing content that looks like it was published 5:00 at p.m. Handling time zones is not optional — it is a fundamental requirement for any serious web project.
The core principle is simple: always store time in UTC in your database.
On the frontend, you should first obtain the user’s time zone and send it to the backend.
The backend can then store this information in the session. Since sessions may expire when users log in or log out, special care must be taken to preserve the time zone information so it does not disappear along with the session.
When a user publishes content that contains time information, their local time should be converted into UTC before being saved to the database. Then, when displaying time data, you get the UTC times from the database and convert it into the user’s local time zone based on the time zone stored in the session. With this approach, users in any region will always see times that match their own local time.
Save UTC timestamp:
Convert it into the user’s local time zone:
Display on HTML:
One important note is that during the process of converting UTC timestamps into the user’s local time zone, you should never directly set the converted value back into your persistent entities. Doing so can easily lead to dirty data and unintended database updates.
In my own project, I use DTOs instead of entities wherever time needs to be displayed. The converted local time is injected directly into the DTO. This approach avoids data pollution, keeps the domain model clean, and also improves overall performance.