如何在javascript中获取不同位置的时区偏移量

时间:2015-07-16 02:14:25

标签: javascript angularjs

我需要使用javascript获取不同地方的当前时间。 我会使用以下方法获得UTC。

function calcUTC() {
    // create Date object for current location
    var d = new Date();

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

    return utc;
}

现在我需要找到特定地点的timezoneOffset,以便我可以将此偏移量添加到utc以获取该位置的当前时间。 这些地方可能是美国,加拿大或其他任何地方。美国有三个不同的时区。请尽可能做到 感谢

2 个答案:

答案 0 :(得分:3)

Date对象的getTime()方法本身返回UTC值。

参考:MDN Date object getTime Method

它说,

  

方法返回对应于时间的数值   根据世界时的指定日期。

您不需要减去或添加本地时区偏移量。

为了计算其他时区的当地时间,您需要找到这些时区的偏移值(这应该考虑夏令时)。

注意:JavaScript Date对象不提供任何将时区作为输入的方法,并返回该时区的偏移量。

此外,如果偏移值是绝对值,则需要减去或添加偏移量,具体取决于时区是在GMT之前还是之后。

答案 1 :(得分:1)

如果您知道您想要时间的地点的时区偏移,那么使用UTC方法非常简单。例如:

_fileman = [NSFileManager defaultManager];
_s_currentPath = [_fileman currentDirectoryPath];
name = _inputName.text;
NSString *temp = [_s_currentPath  stringByAppendingString:name];
NSURL *newDir = [NSURL fileURLWithPath:temp];
[_fileman createDirectoryAtURL: newDir withIntermediateDirectories:YES attributes: nil error:nil];

因此,对于UTC + 0200这样的地方:

/*
** @param {number} offsetInMinutes - Timezone offset for place to be returned
**                                    +ve for east, -ve for west
*/
function timeAt(offsetInMinutes) {
  function z(n){return (n<10? '0':'') + n}
  var now = new Date();
  now.setUTCMinutes(now.getUTCMinutes() + offsetInMinutes);
  return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}

对于你所做的地方UTC-0430:

console.log(timeAt(120));