Skip to content

Instantly share code, notes, and snippets.

@jhkueh
Last active April 16, 2018 03:38
Show Gist options
  • Save jhkueh/74aedabcc9b8be1c24d6e9f41258841e to your computer and use it in GitHub Desktop.
Save jhkueh/74aedabcc9b8be1c24d6e9f41258841e to your computer and use it in GitHub Desktop.
Testing custom datetime on Chrome, when can't change OS' datetime.
// From https://stackoverflow.com/a/39909754
/**
 * 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} hour         - Optional. Default hour 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); // custom new Date here: }(Date, 2018, 3, 16, 9) e.g.

Date.now = function now() {
	return new Date().getTime();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment