It's possible to replace the Date function with your own function that provides the results you want, but doing it before the page uses it will be tricky unless you write a browser extension.
The fundamental bit is (see comments):
// Save the original `Date` function
const OriginalDate = Date;
// Replace it with our own
Date = function Date(...args) {
// Called via `new`?
if (!new.target) {
// No, just pass the call on
return OriginalDate(...args);
}
// Determine what constructor to call
const ctor = new.target === Date ? OriginalDate : new.target;
// Called via `new`
if (args.length !== 0) {
// Date constructor arguments were provided, just pass through
return Reflect.construct(ctor, args);
}
// It's a `new Date()` call, mock the date we want; in this
// example, Jan 1st 2000:
return Reflect.construct(ctor, [2000, 0, 1]);
};
// Make our replacement look like the original (which has `length = 7`)
// You can't assign to `length`, but you can redefine it
Object.defineProperty(Date, "length", {
value: OriginalDate.length,
configurable: true
});
// Save the original `Date` function
const OriginalDate = Date;
// Replace it with our own
Date = function Date(...args) {
// Called via `new`?
if (!new.target) {
// No, just pass the call on
return OriginalDate(...args);
}
// Determine what constructor to call
const ctor = new.target === Date ? OriginalDate : new.target;
// Called via `new`
if (args.length !== 0) {
// Date constructor arguments were provided, just pass through
return Reflect.construct(ctor, args);
}
// It's a `new Date()` call, mock the date we want; in this
// example, Jan 1st 2000:
};
// Make our replacement look like the original (which has `length = 7`)
// You can't assign to `length`, but you can redefine it
Object.defineProperty(Date, "length", {
value: OriginalDate.length,
configurable: true
});
console.log("new Date()", new Date());
console.log("new Date(2021, 7, 3)", new Date(2021, 7, 3));
new Date? On page load? You'll struggle to run anything that could mockDatebefore the page's code runs if so (short of writing a browser extension).