Get current time from specified timezone in JavaScript?

calin92540842 profile image PDS OWNER CALIN (Calin Baenen) ・1 min read

Is there a way I can get the current time of a specified timezone in JavaScript, e.g. "America/Toronto", even whilst my local timezone is "America/Chicago", even if a have to make a JSONP request?



markdown guide

Several libs can help you doing this, depending on your browser target (sometimes it relies on APIs that are not present).


Personally I would definitely go for date-fns which is a much better alternative to moment on all standpoints (lighter, better API). You can have a look at the time zones documentation, the only thing is that it might require a polyfill for some legacy browsers.


It appears moment.js is broken, it always provides the error

moment.js:22 Uncaught TypeError: Cannot read property 'version' of undefined
    at moment.js:22
    at moment.js:16
    at moment.js:18

with these lines of code,:

// Resolves es6 module loading issue
if (moment.version === undefined && moment.default) {
    moment = moment.default;

It works just fine. As per the docs, you need moment, moment-timezone, and some timezone data. In the example below I downloaded both files from moment's website.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <div id="test"></div>
    <script src="moment.min.js"></script>
    <script src="moment-timezone-with-data.js"></script>
      const newYork = moment.tz("2014-06-01 12:00", "America/New_York");
      const losAngeles = newYork.clone().tz("America/Los_Angeles");
      const london = newYork.clone().tz("Europe/London");

      document.querySelector("#test").innerHTML = `
        <p>newYork.format(): ${newYork.format()}</p>
        <p>losAngeles.format(): ${losAngeles.format()}</p>
        <p>london.format(): ${london.format()}</p>

try playing with Date.prototype.getTimezoneOffset()


Thanks for the idea, though I don't know how to convert the timezones, but I might try it sometime.


Moment has pretty much become the go to library for dates in JS.


glad you asked.. here is the holygrail of time formats.. momentjs.com/ your welcome :)