Lee Lee - 3 months ago 7x
Javascript Question

Adding 1 or 2 days to a date string

I have got a string which is maybe

date = "10/08/2011";
English time style.

Its a plain string, so I need to be able to add 1 or 2 days to it.

I have tried a few things but can't work it out as I am normally a PHP guy not JavaScript.

Any help is greatly appreciated.




Why does this seem to be so hard, i've been stuck on this for an hour now..... I want to give the code a plain string which is mm/dd/yyyy - 10/08/2011 and i want back something like 11/08/2011

Why so hard ?? this is why i hate javascript and prefer PHP :-(


It's not all that complex:

//convert string to date
var dattmp = "10/08/2011".split('/').reverse().join('/'),
    nwdate =  new Date(dattmp);

// to add 1 day use:

//to retrieve the new date use

//all in one:
function dateAddDays( /*string dd/mm/yyyy*/ datstr, /*int*/ ndays){
  var dattmp = datstr.split('/').reverse().join('/'),
      nwdate =  new Date(dattmp);
  return [ zeroPad(nwdate.getDate(),10)
          ,nwdate.getFullYear() ].join('/');

//function to add zero to date/month < 10
function zeroPad(nr,base){
  var len = (String(base).length - String(nr).length)+1;
  return len > 0? new Array(len).join('0')+nr : nr;

console.log(dateAddDays("10/08/2011"));    //=> 11/08/2011
console.log(dateAddDays("10/08/2011",-5)); //=> 05/08/2011

if you really want it simple - without using the Date Object:

var datePlus1 = '10/08/2011'.split('/');
datePlus1[0] = Number(datePlus1[0])+1;
console.log(datePlus1.join('/')); //=> 11/08/2011

Here's a small datetime handling object which may be of use.