Convert date to another timezone in JavaScript

For moment.js users, you can now use moment-timezone. Using it, your function would look something like this:

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329

/** 
 * function to calculate local time
 * in a different city
 * given the city's UTC offset
 */
function calcTime(city, offset) {

    // create Date object for current location
    var d = new Date();
   
    // get UTC time in msec
    var utc = d.getTime();
   
    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));
   
    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

this function is useful to calculate time zone value by providing name of a city/country and offset value


Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.

const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);

Here is the one-liner:

function convertTZ(date, tzString) {
    return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));   
}

// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)

// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") 
convertedDate.getHours(); // 17

// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

   

This is the MDN Reference.

Beware the caveat: function above works by relying on parsing toLocaleString result, which is string of a date formatted in en-US locale , e.g. "4/20/2012, 5:10:30 PM". Each browser may not accept en-US formatted date string to its Date constructor and it may return unexpected result (it may ignore daylight saving).

Currently all modern browser accept this format and calculates daylight saving correctly, it may not work on older browser and/or exotic browser.

side-note: It would be great if modern browser have toLocaleDate function, so we don't have to use this hacky work around.