19

Without having to change the date/time of the computer I am debugging, is there a way, either via the dev tools or by running some custom JavaScript in the console, to set / change what time or date Google Chrome thinks it is?

IE so that new Date() returns what you've set the browser to think it is, rather than the system's date.

There are ways around it, but it would be handy to debug different dates / times.

DenverCoder9
  • 1,119
  • 3
  • 16
  • 30
  • 3
    No you can not change the browsers view of the Date – Jaromanda X Oct 07 '16 at 04:57
  • 1
    There are more things JS couldn't do. Here's a tip: If the thing you want to do may cause security problems, it probably can't be done in JS. – Daniel Cheung Oct 07 '16 at 05:01
  • 3
    The specification simply says that a Date called with no arguments creates a Date for "[*the current time*](http://ecma-international.org/ecma-262/7.0/index.html#sec-date-value)". It is up to each implementation how they determine that, but using a host system call seems reasonable. – RobG Oct 07 '16 at 05:05
  • I'm voting to close this question as off-topic because this question is simply how to create a date for a specific date and time, which is default functionality. – RobG Oct 07 '16 at 06:16
  • Possible duplicate of [JavaScript: override Date.prototype.constructor](http://stackoverflow.com/questions/13839318/javascript-override-date-prototype-constructor) – Dan Hlavenka Oct 07 '16 at 15:03

4 Answers4

15

Use:

    var fake_date = new Date("October 6, 2016 11:13:00");

    //overriding date function
    Date = function(){return fake_date;};
    var new_date = new Date();
    alert(new_date);
Rohith K N
  • 845
  • 6
  • 17
  • 2
    What I am after is a setting in Chrome (or any browser for that matter) to set / override what `new Date()` returns, rather than actually change the JavaScript code itself. – DenverCoder9 Oct 07 '16 at 05:07
  • 1
    Using the Date constructor to parse a string is the worst way to create a date. – RobG Oct 07 '16 at 06:12
  • 4
    `Uncaught TypeError: Date.now is not a function` :/ – Luckylooke Feb 06 '18 at 12:26
  • @RobG Unless it's an ISO 8601 date string - then the result is unambiguous. – Roy Tinker Feb 02 '22 at 00:47
  • Thanks. This modified version fixes the Date.now bug: `var fake_date = new Date("July 25, 2022 10:11:00"); //overriding date function Date = function(){return fake_date;}; Date.now = () => fake_date.getTime() var new_date = new Date(); alert(new_date);` – ABCD.ca Jul 23 '22 at 17:18
4

You would need to write a function that wraps new Date and returns a modified version of the date. For example:

/**
 * Overwrite Date constructor with configurable current time
 * @param {object} Date         - The native Date object
 * @param {Number} year         - Optional. Default year to this.
 * @param {Number} month        - Optional. Default month to this.
 * @param {Number} day          - Optional. Default day to this.
 * @param {Number} minute       - Optional. Default minute to this.
 * @param {Number} second       - Optional. Default second to this.
 * @param {Number} milliseconds - Optional. Default milliseconds to this.
 */
Date = function (Date, year, month, day, hour, minute, second, milliseconds) {

    function MyDate() {

        // Get arguments passed into new Date()
        var args = Array.prototype.slice.call(arguments);

        // Add null to start
        args.unshift(null);

        // Call new Date() with the original arguments
        var date = new (Function.prototype.bind.apply(Date, args));

        if (typeof year !== 'undefined' && arguments.length === 0) {
            date.setFullYear(year);
        }

        if (typeof month !== 'undefined' && arguments.length === 0) {
            date.setMonth(month);
        }

        if (typeof day !== 'undefined' && (arguments.length === 0 || arguments.length === 2)) {
            date.setDate(day);
        }

        if (typeof hour !== 'undefined' && (arguments.length === 0 || arguments.length === 3)) {
            date.setHours(hour);
        }
        if (typeof minute !== 'undefined' && (arguments.length === 0 || arguments.length === 4)) {
            date.setMinutes(minute);
        }
        if (typeof second !== 'undefined' && (arguments.length === 0 || arguments.length === 5)) {
            date.setSeconds(second);
        }
        if (typeof milliseconds !== 'undefined' && (arguments.length === 0 || arguments.length === 6)) {
            date.setMilliseconds(milliseconds);
        }

        return date;
    }

    MyDate.prototype = Date.prototype;

    return MyDate;

}(Date);

On the last line you can specify values for overwriting the current time:

}(Date, 1990); // Year
}(Date, 1990, 05); // Year/month
}(Date, 1990, 05, 11); // Year/month/day
}(Date, 1990, 05, 11, 13); // Year/month/day Hour
}(Date, 1990, 05, 11, 13, 05); // Year/month/day Hour:minute
}(Date, 1990, 05, 11, 13, 05, 01); // Year/month/day Hour:minute:second

The benefit of this is that any existing new Date() calls with arguments still work correctly:

new Date(2001, 02, 03);
> Mar 03 2001

Also time is not frozen so the seconds value will increase with the normal clock:

// Year changed to 1990
console.log(new Date());
setTimeout(function(){
    console.log(new Date());
}, 5000);

> Thu Oct 11 1990 17:02:17 GMT+1100 (AUS Eastern Daylight Time)
> Thu Oct 11 1990 17:02:22 GMT+1100 (AUS Eastern Daylight Time)
Ryan Jenkin
  • 864
  • 8
  • 11
  • *setYear* is a legacy method, *setFullYear* should be used instead. Note that setting each parameter separately may result in a different result to setting them all at once, e.g. creating a date for 31 Jan then setting the month to 1 results in a Date for 2 or 3 March, so `date.setFullYear(2016,10,1)` would be much preferred. – RobG Oct 07 '16 at 05:08
  • Close to what I'm after, but still requires a change to the code rather than configuration in the browser. Perhaps what is required is a browser extension... – DenverCoder9 Oct 07 '16 at 05:11
  • I wonder if this works for RelativeTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat – dovidweisz Dec 08 '21 at 18:49
  • Unfortunately this kills the many Date methods that exist and are used nowadays. Otherwise the only answer that attempts an elegant solution where seconds still increment and so on. – loxx Aug 25 '22 at 23:01
  • bro wrote a whole library for a simple thing like that – Andor Németh Mar 17 '23 at 08:37
0

If you use this answer, you might get an error Uncaught TypeError: Date.now is not a function. In that case, you can add .now as a method returning the timestamp integer for the fake date.

const testDate = new Date('Fri Feb 11 2022 10:06:37 GMT-0500 (Eastern Standard Time)')
const returnTestDate = () => testDate
returnTestDate.now = () => testDate.getTime()
Date = returnTestDate

console.log(Date.now()) // returns 1644591997000 every time
JT Houk
  • 171
  • 2
  • 16
  • Please don't post answers that are little more than links to other answers on Stack Overflow. If the questions are the same then flag one as a duplicate. – ChrisF Jun 16 '22 at 08:14
  • Thanks though this version breaks `new Date()`. I commented on the [original question](https://stackoverflow.com/a/39909694/756177) that gets both parts to work. Thanks for the inspiration. – ABCD.ca Jul 23 '22 at 17:20
-7

Just use the setTime function:

var d = new Date();
d.setTime(1332403882588);

The int parameter is the UNIX timestamp in milliseconds.

Œlrim
  • 535
  • 2
  • 13
  • 5
    That creates a Date object for a specific moment in time, it does "*set / change what time or date Google Chrome thinks it is*". – RobG Oct 07 '16 at 05:01