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

后端 未结 3 979
無奈伤痛
無奈伤痛 2021-02-18 21:17

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

3条回答
  •  我在风中等你
    2021-02-18 21:40

    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 };
    

提交回复
热议问题