Skip to content

Instantly share code, notes, and snippets.

@cryocaustik
Created June 19, 2018 23:23
Show Gist options
  • Save cryocaustik/079758e999ec8b1ef07f1d38d593dd39 to your computer and use it in GitHub Desktop.
Save cryocaustik/079758e999ec8b1ef07f1d38d593dd39 to your computer and use it in GitHub Desktop.
JS Date Addition/Subtraction function
function dateAdd(interval, qty, _date) {
if(!_date){_date = new Date();}
if (interval.toLowerCase() === 'd') {
if(qty >= 0){
_date.setDate(_date.getDate() + qty);
} else {
_date.setDate(_date.getDate() - Math.abs(qty));
}
return _date;
} else if (interval.toLowerCase() === 'm') {
if(qty >= 0){
_date.setMonth(_date.getMonth() + qty);
console.log('>=');
} else {
_date.setMonth(_date.getMonth() - Math.abs(qty));
console.log('else');
}
return _date;
} else if (interval.toLowerCase() === 'y' || interval.toLowerCase() === 'yyyy') {
if(qty >= 0){
_date.setMonth(_date.getMonth() + qty*12);
} else {
_date.setMonth(_date.getMonth() - Math.abs(qty*12));
}
return _date;
} else {return NaN;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment