How to add/subtract dates with JavaScript?
Code:
var date = new Date('2011', '01', '02');alert('the original date is ' + date);var newdate = new Date(date);newdate.setDate(newdate.getDate() - 7); // minus the datevar nd = new Date(newdate);alert('the new date is ' + nd);
Using Datepicker:
$("#in").datepicker({ minDate: 0, onSelect: function(dateText, inst) { var actualDate = new Date(dateText); var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1); $('#out').datepicker('option', 'minDate', newDate ); }});$("#out").datepicker();
Extra stuff that might come handy:
getDate() Returns the day of the month (from 1-31)getDay() Returns the day of the week (from 0-6)getFullYear() Returns the year (four digits)getHours() Returns the hour (from 0-23)getMilliseconds() Returns the milliseconds (from 0-999)getMinutes() Returns the minutes (from 0-59)getMonth() Returns the month (from 0-11)getSeconds() Returns the seconds (from 0-59)
Good link: MDN Date
You need to use getTime()
and setTime()
to add or substract the time in a javascript Date object. Using setDate()
and getDate()
will lead to errors when reaching the limits of the months 1, 30, 31, etc..
Using setTime allows you to set an offset in milliseconds, and let the Date object figure the rest:
var now=new Date();var yesterdayMs = now.getTime() - 1000*60*60*24*1; // Offset by one day;now.setTime( yesterdayMs );
startdate.setDate(startdate.getDate() - daysToSubtract);startdate.setDate(startdate.getDate() + daysToAdd);