How to set server time in Node.js


How to set server time in Node.js



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.


Date





Sinon's fake timers are nice for this: sinonjs.org/releases/v6.0.1/fake-timers
– Mark_M
Jun 30 at 20:01





Possible duplicate of stackoverflow.com/questions/43089562/…?
– prototype
Jun 30 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 at 20:06



Date


var d = new Date(2018,06,30, 12, 00);




2 Answers
2



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



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


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.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter