7

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.

Thanks

Lee

UPDATE

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 :-(

Lee
  • 1,280
  • 4
  • 18
  • 35
  • Does this answer your question? [Add days to JavaScript Date](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) – Rajat Jun 18 '21 at 05:53

6 Answers6

17

It's not all that complex:

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

// to add 1 day use:
nwdate.setDate(nwdate.getDate()+1);

//to retrieve the new date use
[nwdate.getDate(),nwdate.getMonth()+1,nwdate.getFullYear()].join('/');

//all in one:
function dateAddDays( /*string dd/mm/yyyy*/ datstr, /*int*/ ndays){
  var dattmp = datstr.split('/').reverse().join('/');
  var nwdate =  new Date(dattmp);
  nwdate.setDate(nwdate.getDate() + (ndays || 1));
  return [ zeroPad(nwdate.getDate(), 10)
          ,zeroPad(nwdate.getMonth()+1, 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;
}

//examples
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:

console.log( '10/08/2011'
  .split('/')
  .map( (v, i) => i < 1 ? +v + 1 : v)
  .join('/') 
);

Here's a small function to convert a date(-time) string to a Date:

const log = Logger(document.querySelector(`pre`));
log(
  `<code>str2Date(\`3/15/2013T12:22\`, \`mdy\`)</code>\n  &gt; ${
    str2Date(`3/15/2013T12:22`, `mdy`)}`,
  `<code>str2Date(\`15-2013-03 12:22\`, \`dym\`)\</code>\n  &gt; ${
    str2Date(`15-2013-03 12:22`, `dym`)}`,
  `<code>str2Date(\`15/3/2013\`, \`dmy\`)</code>\n  &gt; ${
    str2Date(`15/3/2013`, `dmy`)}`,
  `<code>str2Date(\`2013/03/15\`)</code>\n  &gt; ${
    str2Date(`2013/03/15`)}` );

function str2Date(dateStr, ymd = `ymd`) {
  ymd = [...ymd].reduce( (acc, v, i) => ({...acc, [v]: i}), {} );
  const dt = dateStr.split(/[ T]/);
  const [d, t] = [ dt[0].split(/[/-]/), dt[1] ];
  return new Date( `${d[ymd.y]}-${d[ymd.m]}-${d[ymd.d]} ${t || ``}` );
}

function Logger(logEl) {
  return (...args) => {
    args.forEach(arg =>
      logEl.appendChild(
        Object.assign(document.createElement(`div`), {
          innerHTML: `${arg}`,
          className: `logEntry`
        })
      ))
  };
}
body {
  font: normal 12px/16px verdana, arial;
}

.logEntry {
  margin: 5px 0;
}

.logEntry:before {
  content: '• ';
  vertical-align: middle;
}

code {
  background-color: #eee;
  color: green;
  padding: 1px 2px;
}
<pre></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 3
    Note that the simple solution above won't work if you cross a month or year transition. You really want to use the Date object... – Mike C Aug 11 '11 at 11:49
  • @Mike, ofcourse - that's why using a Date Object makes sense. I would advise against the `datePlus1` solution, but it's a possibility. – KooiInc Aug 11 '11 at 11:59
  • 1
    Addition has a higher precedence than logical OR, so you'll want some brackets in there: nwdate.setDate(nwdate.getDate() + (ndays||1) ); – Steven Keith Nov 11 '14 at 11:10
  • This is an overcomplicated, not even close to half-completed approach, especially the hardcoded parts that handle a very specific date format. – Lopofsky Jan 19 '22 at 11:52
16

To add 2 days:

var theDate = new Date("10/28/2011");
theDate.setDate(theDate.getDate()+2);
Mike C
  • 3,077
  • 22
  • 29
  • 2
    this just gives me in unix timestampe by the looks of things :-( – Lee Aug 10 '11 at 16:00
  • 3
    To get a string back, you can do `var theDateString = (theDate.getMonth()+1) + '/' + theDate.getDate() + '/' + theDate.getUTCFullYear();` – Mike C Aug 11 '11 at 11:47
0

I tried this and got the result.

var dat = new Date('2018-03-16');

//use toISOString() to get the string value 2018-03-16T16:38:00.000Z
//substring(0,10) gets 2018-03-16
//reverse to gets 16-03-2018
var ret = dat.toISOString().substring(0, 10).split('-').reverse()

//rearranging to whatever format you want
var t = ret[0];
ret[0] = ret[1];
ret[1] = t;

//result
console.log(ret.join('/'))
Arnold
  • 1
0

You will need to convert the String into a Date-Object. With this you can call the .getDate() and setDate() - Functions to modify the date.

But to achieve this, the date has to be in one of the following formats:

  1. MM/dd/yyyy
  2. yyyy/MM/dd
  3. MM-dd-yyyy
  4. MMMM dd, yyyy
  5. MMM dd, yyyy

So, maybe you would have to switch day and month in your string before converting, as I'm not sure if Month or Day is your first number.

For european Dates, you could change the string into the right format with something like this:

var date = "10/08/2011";
var eurDate = date.substr(3,2) + "/" + date.substr(0,2) + "/" + date.substr(6);

Links that could help you with this:

http://programming.top54u.com/post/Javascript-Convert-String-to-Date.aspx

http://www.adp-gmbh.ch/web/js/date/add_days.html

edit:

JSFiddle with an example: http://jsfiddle.net/4W8yM/11/

GNi33
  • 4,459
  • 2
  • 31
  • 44
0

Try this

var date =  new Date("10/08/2011");

date = new Date(date.setDate(date.getDate()+1));//1 represents 1 day to add so you specify as per your need

var dateStr = date.getDay() + '/' + (date.getMonth() + 1) + '/' + date.getUTCFullYear();
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • this just gives me in unix timestampe by the looks of things :-( – Lee Aug 10 '11 at 15:59
  • argh - thats so close but i need to be able to do it in european style... dd/mm/yyyy any ideas ? – Lee Aug 10 '11 at 16:02
  • You could try my method with substring (edited into my answer). It switches Day and month. On the other hand, the one from Kooilnc should work just fine too, it reverses the string, turning it into a valid format if you are using european Dates. – GNi33 Aug 10 '11 at 16:15
  • @ShankerSangoli - this just gives me 0/10/2011 - i am just about to give up – Lee Aug 10 '11 at 16:24
  • @Lee: Just convert the String with a simple function before. My or Kooilnc's solution should work perfectly fine to get this into the right format -> http://jsfiddle.net/4W8yM/2/ – GNi33 Aug 10 '11 at 16:34
  • its still a mish mash.... it starts with 18/08/2011 in code and doesn't give me 19/08/2011 – Lee Aug 10 '11 at 16:50
  • @Lee: Why is it a mish mash? -> http://jsfiddle.net/4W8yM/11/ The only thing you would need to consider, is that getMonth() returns an integer from 0 to 11. So maybe you'd have to check, if the returned number is <10 and add a 0 before it, before building the final string – GNi33 Aug 10 '11 at 17:28
  • @Lee - What is the currentDay and how many days are you tring to add? I tested my code it works fine. Take a look at this fiddle http://jsfiddle.net/E5PmE/ – ShankarSangoli Aug 10 '11 at 17:38
  • @Shankar - OK i see your example works, but now try 3 days or 7 ?? it doesn't work... i need to be able to add 3,4,7 and 14 – Lee Aug 11 '11 at 08:28
  • @Lee - Did some modifications, please take a look at this fiddle and if this is perfect mark this as an answer. Fiddle http://jsfiddle.net/E5PmE/4/ – ShankarSangoli Aug 11 '11 at 11:53
  • I cannot edit, please edit if you can. The error is the getDay() function which should be getDate(). In fact, getDay() returns 0-6, Sunday through Saturday, while getDate() returns 1-31. – Kar.ma May 03 '17 at 09:17
0

You must enforce a string to be interpreted as date-month-year or or month-date-year, or it will depend on the user's settings.

You can assemble the date from the string to ensure the date-month format:

Date.fromDM=function(string){
    var A= string.match(/([1-9]\d*)/g);
    if(A.length!== 3) throw 'bad date'; 
    return new Date(A[2]*1, A[1]-1, A[0]*1);
}
Date.fromMD=function(string){
    var A= string.match(/([1-9]\d*)/g);
    if(A.length!== 3) throw 'bad date'; 
    return new Date(A[2]*1, A[0]-1, A[1]*1);
}



/*  Date.fromDM('10,08,2011')
return value: (Date)
Wed Aug 10 2011 00:00:00 GMT-0400 (Eastern Daylight Time)
*/

/*Date.fromMD('10,08,2011')
return value: (Date)
Sat Oct 08 2011 00:00:00 GMT-0400 (Eastern Daylight Time)
*/
kennebec
  • 102,654
  • 32
  • 106
  • 127