I need to increment a date value by one day in Javascript. For example, I have a date value 2010-09-11 and I need to store the next date in a Javascript variable.
How can I increment a date by 1 day?
I need to increment a date value by one day in Javascript. For example, I have a date value 2010-09-11 and I need to store the next date in a Javascript variable.
How can I increment a date by 1 day?
Two options for you:
Raw JavaScript:
var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Edit: See also org.life.java's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Or using DateJS:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.