Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 772
Lee Avatar asked Aug 10 '11 15:08

Lee


People also ask

How do you add 5 days to a new date?

// Get current date var date = new Date(); // Add five days to current date date. setDate(date. getDate() + 5); console.

How do you add date and time to string?

var dateValue = new Date("2021-01-12 10:10:20"); Use new Date() along with setHours() and getHours() to add time.


2 Answers

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:

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

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>
like image 87
KooiInc Avatar answered Sep 28 '22 16:09

KooiInc


To add 2 days:

var theDate = new Date("10/28/2011");
theDate.setDate(theDate.getDate()+2);
like image 36
Mike C Avatar answered Sep 28 '22 16:09

Mike C