javascript 如何模拟浏览器的时区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12220717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:37:27  来源:igfitidea点击:

How to mock the browser's timezone?

javascriptgoogle-chromebrowsermockingtimezone

提问by McSas

I want to test a location feature in a web site, to make this test I need to try different time-zones. I obtain the timezone with a javascript code, calling the following function:

我想测试网站中的位置功能,为了进行此测试,我需要尝试不同的时区。我使用 javascript 代码获取时区,调用以下函数:

var offset = new Date().getTimezoneOffset();

Now this function returns to me 180 because I am in Argentina, I need to test with different time-zones. Somebody knows how to do this? Many thanks!!

现在这个函数返回给我 180 因为我在阿根廷,我需要用不同的时区进行测试。有人知道怎么做吗?非常感谢!!

回答by JC Brand

The accepted answer doesn't really mock the Date.getTimezoneOffsetmethod, instead it expects you to use a different method with the same name.

接受的答案并没有真正嘲笑该Date.getTimezoneOffset方法,而是希望您使用具有相同名称的不同方法。

It won't work on Date objects themselves and as Carl Meyer points out, it won't work for libraries like MomentJS.

它不适用于 Date 对象本身,正如 Carl Meyer 指出的那样,它不适用于像 MomentJS 这样的库。

A better way is to override the getTimezoneOffsetmethod on the Dateprototype, so that all instances of Datehave the overridden method.

更好的方法是覆盖原型getTimezoneOffset上的方法Date,以便所有实例都Date具有覆盖的方法。

d = new Date(); // Mon Jul 13 2015 10:58:12 GMT+0200 (CEST)
alert(d.getTimezoneOffset()); // -120, My local "real" timezone.

// Save the original method.
var getTimezoneOffset = Date.prototype.getTimezoneOffset;

Date.prototype.getTimezoneOffset = function () {
    return 160;
}
// Now Date objects will have the mocked timezone offset
alert(d.getTimezoneOffset()); // 160, The mocked timezone.

// Now restore the method to its original version
Date.prototype.getTimezoneOffset = getTimezoneOffset;
alert(d.getTimezoneOffset()); // -120

回答by Brendan

You could use a function for this.

您可以为此使用一个函数。

function getTimezoneOffset() {
  if (DEBUG) {
    return 600; // for Australian Eastern Standard Time
  }

  return new Date().getTimezoneOffset();
}

Where DEBUGis a variable set earlier on to determine whether you're testing or not.

DEBUG先前设置的变量在哪里确定您是否正在测试。

Then use that function throughout your code, instead of the method on the Date object.

然后在整个代码中使用该函数,而不是 Date 对象上的方法。