Javascript 更改浏览器时间以测试 Date() 的返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1976968/
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-08-22 22:11:59  来源:igfitidea点击:

Change browser time to test return value of Date()?

javascript

提问by A00

Is there any way to change the browser's time without manipulating the system clock?

有没有办法在不操纵系统时钟的情况下更改浏览器的时间?

回答by mkrause

The browser doesn't really "have time", it gets its time from the system clock. Of course, if you want to do something particularly nasty, you could override the Date functions.

浏览器并没有真正“有时间”,它从系统时钟中获取时间。当然,如果你想做一些特别讨厌的事情,你可以覆盖 Date 函数。

Date.prototype.getTime = function() { return 1 };
(new Date).getTime(); // 1

So if you wanted to set the time to 1am November 4th 1989, you'd first find the time value:

因此,如果您想将时间设置为 1989 年 11 月 4 日凌晨 1 点,您首先要找到时间值:

(new Date('1989-11-04T01:00:00')).getTime() // Returns 626144400000

Then mock it in browser:

然后在浏览器中模拟它:

Date.prototype.getTime = function() { return 626144400000 };

回答by John Saunders

No. The browser doesn't have a time. The system does.

不。浏览器没有时间。系统可以。

回答by x4u

You can run the browser in a virtual machine (VMWare/VirtualPC/etc.) and change the time of the OS in the VM.

您可以在虚拟机(VMWare/VirtualPC/etc.)中运行浏览器,并在虚拟机中更改操作系统的时间。