I know how to do this in php with date() and mktime() functions, but have no idea how to accomplish the same thing in javascript...
function incr_date(date_str){
//...magic here
return next_date_str;
}
var date_str = '2011-02-28';
console.log( incr_date(date_str) ); //want to output "2011-03-01"
is this even possible with js?
I would use date.js from here - http://www.datejs.com/
Has lots of functions for handling this kind of thing.
First you parse it, then you use
dt.setDate(dt.getDate() + 1)
. You'll have to parse it manually, though, or using DateJS or similar; that format is not yet supported across all major browsers (new Date(date_str)
will not work reliably cross-browser; see note below). And then convert it back to your format.Something along these lines:
Live example
Note that
setDate
will correctly handle rolling over to the next month (and year if necessary).Live example
The above is tested and works on IE6, IE7, IE8; Chrome, Opera, and Firefox on Linux; Chrome, Opera, Firefox, and Safari on Windows.
A note about support for this format in JavaScript: The
new Date(string)
constructor in JavaScript only recently had the formats that it would accept standardized, as of ECMAScript 5th edition released in December 2009. Your format will be supported when browsers support it, but as of this writing, no released version of IE (not even IE8) supports it. Other recent browsers mostly do.First you need to turn your date string into a Date object.
Then you need to add one to the day part of the date.
Although this looks it might end up with the 29th of February, it won't and will give you the 1st March.
I modified this excellent answer https://stackoverflow.com/a/5116693/4021614 to handle both incrementing and decrementing by any amount (using this method https://stackoverflow.com/a/25114400/4021614).
example:
Yes. First you read the date and you convert to a date object, then you add 1 day and return the result
The Date object, which is native in javascript, takes care of all problems arising from leap years and so on.