Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 894
A00 Avatar asked Dec 29 '09 21:12

A00


People also ask

How to get time from a date in JavaScript?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.

How do I change the date on inspect?

Use the calendar icon in the below the General Inspector comments text box on the right side of the screen to select a new return date. Then click the Save Changes button.

How do you mock a date in jest?

Mock the whole Date class with a fixed date instance Date = class extends Date { constructor(date) { if (date) { return super(date); } return currentDate; } }; expect(getCurrentDate()). toEqual(new Date('2019-05-14T11:01:58.135Z')); // Cleanup global. Date = realDate; });


2 Answers

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 };
like image 167
mkrause Avatar answered Oct 04 '22 14:10

mkrause


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

like image 24
John Saunders Avatar answered Oct 04 '22 16:10

John Saunders