Timezone for developers
Farshan Ahamed
Posted on February 8, 2022
When it comes to date and time, developers prefer a value of more than just hours and minutes. It should be a precise value that includes seconds, milliseconds, and in some cases, a timezone.
Most of us are familiar with the term timezone. UTC is a timezone that stands for Universal Time Coordinated. It is equivalent to GMT, which stands for Greenwich Mean Time and has a timezone offset of +0:00. The remaining timezones are all relative to UTC. For instance, The Pacific Time (-8:00) is 8 hours behind UTC.
UTC in database
When storing a date in a database, it is usually in 24-hour format with millisecond precision(yyyy-MM-dd HH:mm:ss.fff
). For example, '2022-02-01 14:25:43.899'. Furthermore, regardless of the time zones in which the developers/applications are located, always save the date and time in the UTC timezone. When converting a time to UTC, the timezone offset is normally subtracted from the actual time. The offset will be one hour less than usual during daylight saving time (summer).
When returning data to the client (browser), adding a 'Z' at the end of the date allows browsers to identify it as UTC and convert it to local time while showing. Most DateTime pickers in modern frameworks are set to convert to UTC by default. There are also some libraries that convert to and from UTC and handle all cases, including DST.
What if we don't use UTC
User A from Australia (+11:00) uploads a photo at time 2022-02-01 11:30 PM
and the same date and time are stored in the database. User B from Canada (-5:00) opens this photo at the same time will see the uploaded date as 2022-02-01 11:30 PM
where the present time of User B is 2022-02-01 7:30 AM
. The uploaded date shown to User B is a future date and that is wrong.
How to solve this issue using UTC
User A from Australia (+11:00) uploads a photo at time 2022-02-01 11:30 PM
and the date and time are converted to UTC (2022-02-01 12:30 PM
) and stored in the database. User B from Canada(-5:00) open this photo at the same time will see the uploaded date as 2022-02-01 7:30 AM
where the present time of User B is 2022-02-01 7:30 AM
. The uploaded date shown to User B is the present date and is correct.
Even though there are many benefits to UTC, there exist cases where we don't need the overhead of using UTC and thus avoid complicating things. Yet, if the date is accessible worldwide then, it is recommended to keep the date in UTC. Since there are different calendar systems in different regions, developers often deal with interesting date and time issues and every new problem is an opportunity to learn.
Posted on February 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.