Adding 1 or 2 days to a date string
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 > ${
str2Date(`3/15/2013T12:22`, `mdy`)}`,
`<code>str2Date(\`15-2013-03 12:22\`, \`dym\`)\</code>\n > ${
str2Date(`15-2013-03 12:22`, `dym`)}`,
`<code>str2Date(\`15/3/2013\`, \`dmy\`)</code>\n > ${
str2Date(`15/3/2013`, `dmy`)}`,
`<code>str2Date(\`2013/03/15\`)</code>\n > ${
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>
To add 2 days:
var theDate = new Date("10/28/2011");
theDate.setDate(theDate.getDate()+2);