The javascript Date object and how to add days to a date variable

JavaScript is not an object oriented language, it’s a prototype based language. This means that you can extend any existing object by just writing a new function for it on-the-fly. Here’s an example:

// add n number of days
Date.prototype.goto = function(n) {
	return this;

Note: Thanks to commenter Joe I use setDate instead of setTime.
Yes I know… GOTO is considered harmful. But so is Edsger Dijkstra. Anyway, this nifty little function will add, or subtract(!), any number of days with an easy to use syntax:

// add n number of days
d = new Date; // today
d.goto(7); // move it to next week
d.goto(-365); // move to last year (well if it isn't leap)

Try it yourself, it’s fun. Now to make things more interesting, you can make a generic function (erm.. method?!) that will calculate the number of days since the Epoch

Date.prototype.days = function() { return parseInt(this.getTime() / (1000*24*60*60)); };

This makes stuff like comparing dates and calculating differences way easier. E.g. check out this one for calculating the number of working days between two dates:

Date.prototype.workdays = function(d2) {
	var start = new Date(this);
	var end = d2;
	var ret = 0;
	var diff = end.days() - start.days();
	if (diff > 0)
		// up to 1 year
		while (start.days() < end.days() && ret < 3650)
			start.goto(1); // move to next day
			if (start.getDay() != 0 && start.getDay() != 6)
	return ret;

5 thoughts on “The javascript Date object and how to add days to a date variable

  1. Yup, fails due to daylight savings time:

    >>> (new Date(2010, 9, 8)).goto(30);
    Sun Nov 07 2010 00:00:00 GMT-0400 (Eastern Daylight Time) {}
    >>> (new Date(2010, 9, 8)).goto(31);
    Sun Nov 07 2010 23:00:00 GMT-0500 (Eastern Standard Time) {}

  2. Thanks for that code. This works and fixes the Daylight Saving issue.

    Date.prototype.goto = function(n) {
    var thisUTC = this.getTimezoneOffset();
    if (thisUTC!=this.getTimezoneOffset()) { this.setTime(this.getTime()+(this.getTimezoneOffset()-thisUTC)*60000); }
    return this;

    1. What’s wrong with just using setDate() instead of setTime? Adding to the date (day of the month) will automatically adjust the month & year.

      So if it’s 28th Sept and you do x.setDate(x.getDate()+3), the date in x will be 1st Oct.

      1. Yes I think I saw this before… I was assuming setTime would do the same. Since it doesn’t the code is not to be trusted. I’ll rewrite based on your input. Thanks, Joe.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s