Detecting timezones in the browser and on NodeJs with JsTimezoneDetect

Finding the timezone

Initially we had to detect the timezone of the user’s browser and send that as a header attribute to our API server so we could convert the dates in the response to the user’s local timezone. In our application we store all the dates in UTC format to have a common baseline.

Our API endpoints are consumed from two different sources

  • Web app coded with angular
  • NodeJS SDK

So when a request is made to our API server we set the X-User-Timezone header attribute with the timezone name, eg; America/New_York

A note to take from there is that you don’t ever want to use the timezone abbreviation, eg; IST. IST is ambiguous, it could mean Irish, Indian or Israeli time. Always stick with the timezone name instead. The name, such as “Asia/Jerusalem” will always give you the correct offset, in the case of Israel +2:00 or +3:00

The native javascript Date specification has minimal support for timezones and only provides the offset in minutes. For example, here in Toronto during the summer we have an offset of minus 4 hours from UTC. Starting a node shell and running the following instructions we can confirm the results:

var d = new Date();
> d.getTimezoneOffset()
> d.getTimezoneOffset() / 60

Even though we have a -4 offset a difference of 240 minutes is returned. Quoting from MDN documentation “The time-zone offset is the difference, in minutes, between UTC and local time”

With that being said, there is no easy way to find the timezone name using the native javascript Date object. Also instead of trying to recreate the logic to parse timezones for every application it is much better to utilize a third party library to do the work. The only library I could find that does a good job in parsing time zones is called JsTimeZoneDetect

With jsTimeZoneDetect you can find the timezone with the following commands:

var timezone = jstz.determine();