user616
user616

Reputation: 855

Override Date constructor

Is there a way to override the Date constructor to check for a valid date before creating a new Date object? For example i have some situations where dates are dynamically created and wrong dates are created. So if i create let d = new Date(2019, 1, 31) i want the date constructor to check that the day is within bounds of how many days are in the month to be created.

So currently if i run let d = new Date(2019, 1, 31) it will create a date of March 3 2019 because there are only 28 days in February. I want the date constructor to verify that first and if the day is out of bounds then create the date as let d = new Date(2019, 1, 28) which is February 28 2019.

Upvotes: 0

Views: 702

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138457

Sure, you can override everything in JS:

 const OriginalDate = Date;
 Date = function(...args) {
   // fancy checks
   return new OriginalDate(...args);
 };

But be aware: Changing JS internals might break code somewhere on the page, so you should never do that in larger production projects.

Upvotes: 1

Related Questions