问题描述
我想测试网站中的位置功能,要进行此测试,我需要尝试不同的时区.我使用 javascript 代码获取时区,调用以下函数:
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:
var offset = new Date().getTimezoneOffset();
现在这个函数返回给我 180 因为我在阿根廷,我需要使用不同的时区进行测试.有人知道怎么做吗?非常感谢!!
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!!
推荐答案
接受的答案并没有真正模拟 Date.getTimezoneOffset
方法,而是希望您使用具有相同功能的不同方法名字.
The accepted answer doesn't really mock the Date.getTimezoneOffset
method, instead it expects you to use a different method with the same name.
它不适用于 Date 对象本身,正如 Carl Meyer 指出的那样,它不适用于 MomentJS 等库.
It won't work on Date objects themselves and as Carl Meyer points out, it won't work for libraries like MomentJS.
更好的方法是覆盖 Date
原型上的 getTimezoneOffset
方法,以便 Date
的所有实例都有被覆盖的方法.
A better way is to override the getTimezoneOffset
method on the Date
prototype, so that all instances of Date
have the overridden method.
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
这篇关于如何模拟浏览器的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!