Convert date to another timezone in JavaScript

2018-12-31 01:32发布

I am looking for a function to convert date in one timezone to another.

It need two parameters,

  • date (in format "2012/04/10 10:10:30 +0000")
  • timezone string ("Asia/Jakarta")

The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab

Is there an easy way to do this?

20条回答
流年柔荑漫光年
2楼-- · 2018-12-31 02:00

I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime() to the corresponding number of milliseconds, and back again.

date = new Date('2016-05-24T13:07:20');
date = new Date(date.getTime());

For example, date.getHours() will now return 15 instead of 13 if you are, like me, in Austria (and it's summer).

I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 02:01

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();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // 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

查看更多
登录 后发表回答