It's 2024, and I'm still astounded to see applications riddled with local time usage for timestamps. Juggles between time zones, daylight saving time, and all the other hocus-pocus associated with it seem like unwanted baggage for developers. Today, we pledge to end this madness and swear by UTC for all our timestamp requirements.
Timestamps and Time zones
A timestamp is a label that indicates the specific date and time an event occurred. It's like you time-captured a moment and stamped it for reference. It denotes a point in history. But how you read it will depend on which “time zone” you are using. A timestamp which reads 12:00 am on British Standard Time, will read 5:30 am on Indian Standard Time.
Time zones are geographical regions that follow a standard time defined by their offset from the Universal Coordinated Time (UTC). However, the rules governing these time zones can sometimes be a convoluted conundrum to decipher.
The UTC Advantage
Coordinated Universal Time (UTC) is the global standard for regulating clocks and time. It establishes a reference for the current time and forms the basis for civil time and time zones.
UTC is deterministic and unambiguous. It's determined from highly precise atomic clocks and is not subject to the whims of time zones or daylight saving time.
Coding for UTC eradicates daylight saving time, saving you from the horrors of ambiguous time. Moreover, the fixed rules make operations like calculating differences between timestamps a breeze. Extra brownie points for no vanishing or extra hours!
Users vs Servers
Your users are everywhere in the world. Some of them are also wanderers, traveling across time zones. Their primary concern lies in knowing what time an event happened. Servers, on the contrary, remain static. If you tell a user that they withdrew money at 3:00 AM tomorrow, they will be perplexed.
Daylight Saving Time: More Trouble Than It's Worth?
Daylight Saving Time has long been thought to be a beneficial strategy. But the reality seems to tiptoe on the contrary. Opting for this leads to an unexpected hour popping out of or vanishing into oblivion—not to mention the excessive chaos it causes!
Ignoring UTC: A Pandora's Box
Should you shun the UTC and stick to local time, prepare for a swarm of bugs, angry users, and disgruntled developers on your plate. Your coded masterpiece could morph into an unsolvable labyrinth filled with timezone turbulence, Daylight Saving Time debacle, and other trickery of time manipulation. Consequently, a chunk of your time debugging, with little to spare for actual development.
Using UTC in Your Code
Set your Server to UTC
Ensure that you set your servers to UTC. This will save you the hassle of converting time zones and daylight saving time. By default, every piece of code you write will be using UTC.
To do this in a Linux server with systemd
, you can set the timezone using the timedatectl
command:
timedatectl set-timezone UTC
Set your Application to UTC
If you can't set your server to UTC, consider using a library to handle time in UTC. Java, for instance, has a Clock
you can utilize to get the current time in UTC. Similarly, other languages allow you to set the timezone for your application.
Some examples:
class Example {
public static void main(String[] args) {
// A clock that returns the current time using UTC time-zone.
Clock clock = Clock.systemUTC();
LocalDateTime now = LocalDateTime.now(clock);
System.out.println(now);
}
}
class Example {
public static void main(String[] args) {
// Set default timezone to UTC
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Get the current time,
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
}
}
from datetime import datetime
from pytz import utc
# Get the current time in UTC
# This will return a timezone-aware datetime object
# with the timezone set to UTC
now = datetime.now(utc)
Timestamps in databases
When storing timestamps in databases, always use UTC. It will ensure consistency across your application and prevent timezone-related bugs. Most databases use the TIMESTAMP
data type to store timestamps in UTC. When displaying them on the front end, you can format them to the user's timezone.
Timestamps in APIs
Adopt the ISO 8601 format with UTC timezone for your APIs. Make it a point to state the timezone explicitly in your response.
{
"timestamp": "2024-01-01T12:00:00Z"
}
Using ISO 8601 with UTC timezone will ensure your timestamps are unambiguous and consistent across different systems.
Displaying Time to Users
When displaying timestamps to users, always convert them to the user's timezone. It will ensure that the user sees the time in their local time, making it easier to understand. You can use libraries like `moment.js` in JavaScript to handle timezone conversions easily.
const timestamp = "2024-01-01T12:00:00Z";
const localTime = moment(timestamp).local();
console.log(localTime.format("YYYY-MM-DD HH:mm:ss"));
If needed, you can also display the timezone and timestamp to avoid confusion. You can also provide an option for users to change the timezone in your application settings.
Scheduling Events: An Exception to the Rule
If future schedules are required, use user-defined time, date, and timezone. Do not convert them to UTC; store them as they are.
But Why?
Users anticipate the event to occur at that precise time in their respective time zones. An unexpected shift due to conversion to UTC, courtesy of the absurd rules of DST, can be a source of confusion.
Timezone Handling: (not) A Cake Walk
Correct and effective timezone is hard. However, therein lies the art of coding—tackling problems head-on and emerging victorious. And using UTC for your timestamps definitely makes that journey a tad bit less winding. So save yourself from the time zone madness and just F**ing use UTC!