Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how can I increment a date string (YYYY-MM-DD) by 1 day

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?

like image 505
Haroldo Avatar asked Nov 30 '22 04:11

Haroldo


1 Answers

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.

like image 60
T.J. Crowder Avatar answered Jan 12 '23 00:01

T.J. Crowder