O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Calculating a Previous or Future Date

NN 2, IE 3

Problem

You want to obtain a date based on a specific number of days before or after a known date.

Solution

The basic technique is to create a date object with a known date, and then add or subtract any number of units from that known date. After that, you can read the components of the modified date object to obtain the string or numerical representation of the date.

For example, we'll calculate the date that is 10 days from the current date. After creating a date object for now, a statement reads the date component (a calendar date within the month) and then sets the date value ahead by 10 days:

var myDate = new Date( );
myDate.setDate(myDate.getDate( ) + 10);

At this point, the myDate object contains the future date in milliseconds, irrespective of months, dates, and years. But if you then read myDate's string version (or locale string in recent browsers), you see the future date correctly calculated:

document.myForm.deadline.value = myDate.toLocaleDateString( );

Discussion

You can move the date forward or back by any increment you like, even when it doesn't seem logical. For example, if a date object is currently pointing to the 25th of a month, you can get the date 10 days in the future by adding 10 to the date:

myDate.setDate(myDate.getDate( ) + 10);

Even though 25 plus 10 is 35, the date object corrects for the number of days in the object's month, and calculates the correct date in the following month 10 days after the 25th.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required