2.10 Calculating a Previous or Future Date
NN 2, IE 3
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( );
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.
A date object has numerous functions for getting and setting components of the date, ranging from the millisecond to the year. Table 2-3 shows the most common methods and their value ranges.
All of these methods deal with time in the client computer's local time zone. If you need to work on a more global scale, see Recipe 15.8.
2.10.4 See Also