I am developing a browser application that is sensitive to the current date.
Throughout my application's code, I call new Date
and perform calculations based on the current time and render the view accordingly.
In order to test my application for different potential calendar days, I would have to constantly change my system clock to the past or future, which is an annoyance and probably not healthy for my computer.
So purely for testing purposes (I would never use this code in production), I decided to override the built-in Date
constructor by doing this in the console:
// create a date object for this Friday:
var d = new Date(2012, 0, 20)
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d}
With this assumption in mind, I tried this and got strange results:
var now = new Date
Sat Apr 07 2012 00:00:00 GMT-0400 (EDT)
now = new Date
Tue Jul 10 2012 00:00:00 GMT-0400 (EDT)
now = new Date
Wed Jul 09 2014 00:00:00 GMT-0400 (EDT)
now = new Date
Wed Jun 07 2023 00:00:00 GMT-0400 (EDT)
...and so on....
My question is, what exactly is going on here?
If I overrode the constructor to return a static date, why does it give unrelated and constantly incrementing dates?
Also, is there an effective way I can override the Date constructor to return a static date in the future without having to go through all date instantiation calls in my code and modifying the output?
Thanks in advance.
EDIT:
I tried my code in a fresh window and it worked as expected.
It seems the culprit was the jQuery UI datepicker plugin which was calling its "refresh" method. When I disable its call, the date overriding works normally, but as soon as I use the datepicker, the strange behavior above occurs.
No idea why this popular plugin would somehow affect something global like this. If anyone has any ideas, let me know.
Sorry for not figuring out the true culprit earlier.
I also faced this problem and ended up writing a module for that. Perhaps it's useful for somebody:
Github: https://github.com/schickling/timemachine
timemachine.config({
dateString: 'December 25, 1991 13:12:59'
});
console.log(new Date()); // December 25, 1991 13:12:59
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With