提问者:小点点

在JavaScript中将日期转换为另一个时区


我正在寻找一个函数,以转换日期在一个时区到另一个。

它需要两个参数,

  • 日期(格式为“2012/04/10 10:10:30+0000”)
  • 时区字符串(“Asia/Jakarta”)

时区字符串在http://en.wikipedia.org/wiki/zone.tab中描述

有什么简单的方法可以做到这一点吗?


共3个答案

匿名用户

null

var aestTime = new Date().toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
console.log('AEST time: '+ (new Date(aestTime)).toISOString())

var asiaTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Shanghai"});
console.log('Asia time: '+ (new Date(asiaTime)).toISOString())

var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
console.log('USA time: '+ (new Date(usaTime)).toISOString())

var indiaTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata"});
console.log('India time: '+ (new Date(indiaTime)).toISOString())

匿名用户

对于moment.js用户,现在可以使用moment-timezone。 使用它,您的函数将如下所示:

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

匿名用户

无耻地窃取自: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();
}

该函数通过提供城市/国家名称和偏移值来计算时区值