3

I would like to set (mock) my custom time to the Node.js server for testing purposes. Something like this:

console.log(new Date());
// Sat Jun 30 2018 20:00:00 GMT+0100
//                 ^^
someFunctionToSetTime('Sat Jun 30 2018 12:00:00 GMT+0100')
//                                     ^^
console.log(new Date());
// Sat Jun 30 2018 12:00:00 GMT+0100
//                 ^^

How do I do this?

P.S. I don't really want to fake the Date class.

user7637745
  • 965
  • 2
  • 14
  • 27
igorpavlov
  • 3,576
  • 6
  • 29
  • 56
  • Sinon's fake timers are nice for this: http://sinonjs.org/releases/v6.0.1/fake-timers/ – Mark Jun 30 '18 at 20:01
  • Possible duplicate of https://stackoverflow.com/questions/43089562/node-js-set-system-date-time? – prototype Jun 30 '18 at 20:04
  • Why not just use `Date` constructor with parameters? i.e. `var d = new Date(2018,06,30, 12, 00);` – The Reason Jun 30 '18 at 20:06
  • 1
    Because it is about mocking the current user's time. In the real code it just calls `new Date()`, but in the test it needs to return a mocked value. – igorpavlov Jul 16 '18 at 19:13

2 Answers2

4

Just monkey patch the Date constructor:

let now = 'Sat Jun 30 2018 12:00:00 GMT+0100';

{
   const oldDate = Date;
   Date = function(...args) {
     if(args.length) {
       return new oldDate(...args);
     } else {
      return new oldDate(now);
    }
  };
  Date.parse = oldDate.parse;
  Date.UTC = oldDate.UTC;
  Date.now = () => +(new Date());
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    This works. But it also seems to remove some aspects of the native `Date` class. For example it removes the `Date.now` function. My project had dependencies which rely on `Date.now`, so this method breaks them – defraggled Sep 26 '21 at 05:55
  • @defraggled sure, touching such a fundamental class will always break something. This should really only be used for testing purposes. I've added all static methods for completeness. – Jonas Wilms Sep 26 '21 at 10:34
0

First option : Without external modules you can use this to get timezone Date and time in node.js var myDate = new Date().toLocaleString('en-US', { timeZone: 'Europe/Paris' });

Second option : Use momentjs timezone witch allows you to set your location and more... just check the documentation.