Is there any way to change the browser's time without manipulating the system clock?
Asked
Active
Viewed 3.8k times
26
-
3The short answer is no. What are you trying to do, exactly? – Jon B Dec 29 '09 at 21:13
-
1So the Date() function returns a date different from my timezone. – A00 Dec 29 '09 at 21:16
-
1@A00: you might want to rephrase your question (or ask a different one), then, as that's a completely different problem. – Jon B Dec 29 '09 at 21:18
-
I want to do this so that I can do e2e testing with cypress and assert that the system behaves differently at different times. – Chris Oct 13 '20 at 19:24
4 Answers
46
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.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:
(new Date('1989-11-04T01:00:00')).getTime() // Returns 626144400000
Then mock it in browser:
Date.prototype.getTime = function() { return 626144400000 };

RJFalconer
- 10,890
- 5
- 51
- 66

mkrause
- 1,370
- 1
- 10
- 11
-
I've tested it and it works, thanks for this awesome trick. But I have questions, Let's use a dummy website (https://www.timeanddate.com/timer/) Set a timer (say for 5 mins) Now, 1. After setting the time to a future point, we can skip time in the timer as well but why the timer is moving forward after that? Haven't I just broken the function by telling it to give the fixed time? 2. If I set the time to a past point than now, the timer stops working, why is that. – Cyber Avater Mar 10 '22 at 14:19
8
You can run the browser in a virtual machine (VMWare/VirtualPC/etc.) and change the time of the OS in the VM.

x4u
- 13,877
- 6
- 48
- 58
0
I suggest using timemachine to override system's time before each test and resetting it after each test.

ds1371dani
- 63
- 1
- 6