Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  128] [ 1]  / answers: 1 / hits: 16358  / 14 Years ago, fri, february 25, 2011, 12:00:00

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?


More From » jquery

 Answers
17

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:



function incr_date(date_str){
var parts = date_str.split(-);
var dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = + dt.getFullYear();
parts[1] = + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = 0 + parts[1];
}
parts[2] = + dt.getDate();
if (parts[2].length < 2) {
parts[2] = 0 + parts[2];
}
return parts.join(-);
}


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.


[#93582] Wednesday, February 23, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jillcalistay

Total Points: 561
Total Questions: 94
Total Answers: 114

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
jillcalistay questions
Mon, Jan 3, 22, 00:00, 2 Years ago
Mon, Feb 15, 21, 00:00, 3 Years ago
Mon, Nov 16, 20, 00:00, 4 Years ago
Sat, Aug 1, 20, 00:00, 4 Years ago
;