Overriding the Javascript Date constructor?

javascript date from string
javascript date format
typescript date
date prototype
javascript epoch to date
javascript date library
javascript new date timezone
js time machine

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 tested your code:

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

var now = new Date()
console.log(now);

now = new Date()
console.log(now);

now = new Date()
console.log(now);

now = new Date()
console.log(now);

And the result ???? Why so different?

Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}

EDIT:

I saw that whenever you interact with the Date Picker, the behavior goes different. Try another test, change the now is something like interact with Date Picker:

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

var now = new Date();
var another = new Date();
console.log(now);

another.setDate(13);

now = new Date()
console.log(now);

And the result is:

Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 13 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}

So, what goes wrong? You already overridden core Date function by

Date = function(){return d;}; // after construction, all date will be d (2012-01-20)
var now = new Date(); // you instantiate a date, but actually now variable is d (2012-01-20)
var another = new Date(); // you instantiate a date, but another is still d (2012-01-20)
another.setDate(13); // change another date to 13 is to change now to 13 (because now and another is still one d)

now = new Date() // still d
console.log(now); // print out now (2012-01-13)

So, you overrides core Date function by a function that causes all date use the same (just one) instance, which is d (2012-01-20). Change any dates affect others.

To understand the concept of overriding in JavaScript, let us first revise the concept of this.date = "This method overrides the default constructor of Date class."; Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. JavaScript Demo: Date Constructor.

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

Override Date.now() based on OS time when Node returns incorrect current date a detection of this spread between JavaScript Date and OS Date and an override of the now() function on the Date const d = Date.parse(da). Types of Overriding in JavaScript. There are no types of overriding defined in JavaScript. However, based on the behavior of the programming language, we can say that method overriding in JavaScript works in the following ways. 1) The First Behaviour. The first way is the one we saw above when we defined a method to override the default Date constructor of JavaScript. This is in a way similar to the third way illustrated below because all objects in JavaScript are an instance of the Object

Give this a shot.

var d = new Date(2012, 0, 20);
// undefine date so that it will only return what your function returns
Date = undefined;   
Date = function(){return d;}

Modifying the prototype to point to your object should do the trick.

I believe the strange behavior you were experiencing earlier was that privately Date holds some notion of time, and since the prototype points to that internal clock, you were getting random times.

Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  In JavaScript, the constructor property returns the constructor function for an object. For JavaScript dates the constructor property returns function Date () { [native code] } For JavaScript numbers the constructor property returns function Number () { [native code] } For JavaScript strings the constructor property returns function String () { [native code] }

This is working for me.

I.E how to return process time 1 minute back

Date = class extends Date{
     constructor(options) {
       if (options) {
         super(options);
       } else {
         super(Date.now() - 1000 * 60);
       }
     }
   };

I have a few JavaScript Date object additions, and I'm not entirely sure above for the override route, all is well, and my functions are there. Sets a date to a specified number of milliseconds after/before January 1, 1970. Sets the day of the month of a date object, according to universal time. setUTCFullYear () Sets the year of a date object, according to universal time. Sets the hour of a date object, according to universal time. setUTCMilliseconds ()

Alex Stanovsky's answer almost did it for me but this modification made the constructor work like before when given parameters.

    Date = class extends Date {
      constructor(...options) {
        if (options.length) {
          super(...options);
        } else {
          super(2019, 2, 11, 19, 19);
        }
      }
    };

Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC. Constructor. new Date(); new  In JavaScript, there’s a distinction between a constructor function of an inheriting class (so-called “derived constructor”) and other functions. A derived constructor has a special internal property [[ConstructorKind]]:"derived" .

class Animal { constructor ( name ) { this . speed = 0 ; this . name E.g. Date.​prototype. Now let's move forward and override a method. Constructor Overloading Example. Here we are creating two objects of class StudentData. One is with default constructor and another one using parameterized constructor. Both the constructors have different initialization code, similarly you can create any number of constructors with different-2 initialization codes for different-2 purposes.

JavaScript | date.setDate() function. The date.setDate() is an inbuilt function in JavaScript DateObj is a valid Date object created using Date() constructor in which we want to set the date E() function · How to override a JavaScript function ? Javascript supports overriding but not overloading. When you define multiple functions in Javascript and include them in the file then the last one is referred by the Javascript engine. Original Javascript file which we refer:

Types of Constructors in JavaScript. There are two types of constructors in JavaScript. 1. Built-in Constructors. These are the readily available constructors that come bundled with the execution environment. The user simply needs to invoke them and viola, the work’s done. Examples of built-in constructors are Array, Date, and Object. 2.

Comments
  • I can't reproduce the incrementing behavior you are seeing. What browser / environment are you in?
  • I'm in Chrome 17 on OSX 10.7.2.
  • I wrote a library that allows overriding the Date constructor and setting the time and time zone for testing purposes: github.com/plaa/TimeShift-js
  • Thanks, see my above edit for what caused the behavior. I will upvote when I have enough rep.
  • Ah I see. All newly constructed dates share the same object so modifications to one affect the others. I think the solution for my purposes is to deliver a cloned object from the constructor. Thanks for your help!
  • If you're trying out this solution, note that just importing the library will change your new Date() result! Either import it with a require only when you actually want to change the date, or call reset() in cases where you don't want to adjust the date (e.g. if you're setting the date sometimes with a debug environment variable, our use case). github.com/schickling/timemachine/issues/8
  • Also to use timemachine, you'll want to add .parse(), otherwise other libraries can easily break. As so: github.com/cardamo/timemachine/commit/…
  • Thanks for the suggestion, but that wasn't actually the issue. See my above edit for what caused the behavior. I will upvote when I have enough rep.
  • @amchang87: In any case line Date = undefined; no have any sence in your code.
  • You are a genius :)
  • It is working normally on chrome. It is not working on IE 11 because it ES5. Any idea
  • This allows the usage of Date.now to continue to work afterwards and anything that relies on a specific time, beautiful.
  • It is working normally on chrome. It is not working on IE 11 because it ES5. Any idea