right now this code works for tomorrow and next month – weekend use to work , except now that it is approaching the end of the month it is causing an error. my startdate is set to 8/31/12 and enddate is 8/34/12 (which is obivously going to throw an error when converted into DateTime in Sql.)
I am successfully doing math to add a day , and to add a month , but when it comes to adding days into the next month it breaks. I think I understand why this is hapening , it is getting date – “29” turning it to into int then adding – I suppose I will get the same problem for “next month” in December.
My question is what is the proper way (or any working way) to add days to javascript date, where it understands the days of the month.
var d = new Date();
var startdate;
var enddate;
if ($('._tomorrow').attr("checked") == "checked") {
startdate = [d.getMonth() + 1, d.getDate() + 1, d.getFullYear()].join('/');
enddate = [d.getMonth() + 1, d.getDate() + 2, d.getFullYear()].join('/');
}
if ($('._weekend').attr("checked") == "checked") {
startdate = [d.getMonth() + 1, d.getDate() + 6 - d.getDay(), d.getFullYear()].join('/');
enddate = [d.getMonth() + 1, ( d.getDate() + 6 - d.getDay()) + 2, d.getFullYear()].join('/');
}
if ($('._nextmonth').attr("checked") == "checked") {
startdate = [d.getMonth() + 2, 1, d.getFullYear()].join('/');
enddate = [d.getMonth() + 2, 29 , d.getFullYear()].join('/');
}
To add a specified number of days, create a new
Dateobject and then used.setDate(d.getDate() + n)wherenis the required number of days to add.If you then call
getYear(),getMonth()andgetDate()again you will find that they’ve all been “corrected” to valid values:Adding months is not so straightforward, because you need to define what happens when the following month is shorter than the current month – e.g. what date is “one month after 31st January” ?
Calculating the start of the next month is easy enough, though!
See http://jsfiddle.net/alnitak/nTSMg/