Tuesday, March 19, 2024

JavaScript: Working with Time Zones

If your application(s) include date and time information, there’s a good chance that you’ll have to deal with time zones. In a nutshell, that requires adding or subtracting hours to a DateTime value to express it in another time zone. Sounds simple enough on the surface. However, in practice, it’s incredibly daunting. Not only do you need to determine the time zones of both locations, but you may even have to account for time zone changes due to political and/or economic reasons. Moreover, you’ll likely need to deal with the abomination known as Daylight Savings Time. Finally, as if to add insult to injury, JavaScript’s native facilities for working with time zones are spotty at best, so you could find yourself having to perform all sorts of complex date and time calculations yourself.

Are you intimidated yet? As the wise old Yoda once said: “You will be. You will be.” All kidding aside, this tutorial aims to prepare you for battle by providing a bird’s eye view of the battlefield and weapons that you’ll need to be successful.

Know Thine Enemy

In truth, time zones are a good thing; they allow different regions to experience a 24 hour day in much the same way. Without time zones, it would be dawn at 7 PM somewhere. By dividing the Earth into 24 equal time zones that follow the sun, everyone gets days and nights that happen around the same (clock) time.

Each time zone is defined by its offset (difference) from Coordinated Universal Time (UTC), the world’s time standard. UTC time changes 1 hour forward and backward, corresponding to a 1-hour difference in mean solar time for every 15 degrees east or west of the prime meridian (0° longitude) in Greenwich, a suburb of London, in the United Kingdom. The offset is expressed as either UTC- or UTC+ and the number of hours and minutes.

At least, that’s the general idea. In reality, time zones have been drawn to match up with both internal and international borders so that we get something that looks like this:

Time-Zones-Around-the-World

To make matters worse, many regions utilize Daylight Saving Time (DST), which changes the time zone name and time during the DST period. The areas that don’t use DST remain in the standard time zone all year. For example, California uses Pacific Daylight Time (PDT) during the DST period but Pacific Standard Time (PST) during the rest of the year.

Ok, it’s bad. Hold on; we’re not quite done yet.

Local Time Zone Names and Abbreviations

To add fuel to the fire, many regions implement their own local time zone names within the same time zone. For example, Miami, Florida, is 5 hours behind UTC (UTC-5), and the standard time zone is Eastern Standard Time (EST). Meanwhile, Havana, Cuba’s local time zone, is called Cuba Standard Time (CST), despite being in the same time zone of UTC-5!

Yet another source of confusion is that some time zones’ names in completely different places utilize the exact same abbreviation! For instance, India Standard Time (IST) and Israel Standard Time (IST) have the same abbreviation, despite having completely different UTC offsets of UTC+5:30 and UTC+2:00. (Did I mention that some time zone offsets include half hours, i.e., UTC+5:30?)

Time Zone Localization in JavaScript

JavaScript’s Date object represents a single moment in time in a platform-independent format. Date objects contain a number representing the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. Hence, the time value at the heart of a Date object is UTC, while methods that fetch the date and time or its components all return values in the local (i.e., host system) time zone and offset.

There are a couple of notable methods that do not automatically localize results:

  1. The getTime() method returns the number of milliseconds since 1970, UTC time, without localization.
  2. The toISOString() method always returns the date in UTC time, which is confirmed by the letter “Z” at the end of the string. It stands for the Zero time zone, indicating that it has a 0 offset from the Coordinated Universal Time (UTC), as well as Zulu Time Zone, which is often used in aviation and the military as another name for UTC +0.

We can see JS localization in action by creating a new date of “2020-01-01”. Without time data, JavaScript sets it to midnight in London. When I output the stored date, it is presented with my local time zone offset of “GMT-0500”, which is actually early New Year’s Eve here in North America:

Time Zones in Javascript

 

GMT stands for Greenwich Mean Time, which is the clock time at the Royal Observatory in Greenwich, U.K. located at longitude 0. The GMT system became the world time standard until Jan. 1, 1972.

Greenwich-clock.jpg

JavaScript Date/Time Libraries to the Rescue!

Several specialized libraries have cropped up to make dates work across multiple time zones. These include:

  1. moment.js
  2. date-fns
  3. Luxon
  4. DayJS
  5. ms
  6. js-joda
  7. Spacetime

Moment.js is still widely regarded as the king of the JavaScript date libraries, despite being designated a legacy project by its maintainers in 2020. Who will rise up to claim JS date library supremacy remains to be seen.

Conclusion

I once posed a question to a popular developer community board how best to architect an app that dealt with multiple time zones. Their answer: don’t! So, of course, I did. I have since come to understand their dire warnings! Having since gained some experience with time zone management, I will share what I’ve learned in order to make it easier for those who follow. In up-coming articles, we’ll perform some common time zone calculations using some of the above libraries.

 


Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured