If you take a look at the Date Object and its methods and properties in JavaScript, you'll notice that JavaScript bases its time on milliseconds since 1970.
Knowing that you can easily modify dates by adding or subtracting milliseconds.
/**
* subtractDateFromDate
* Use the millisecond value insert both elements to calculate a new date.
* @param d1 {Date}
* @param d2 {Date}
*/
function subtractDateFromDate(d1, d2) {
return new Date(d1.getTime() - d2.getTime());
}
/**
* addDaysToDate
* Create a new Date based on the milliseconds of the first date,
* adding the milliseconds for the extra days specified.
* Notice that days can be a negative number.
* @param d {Date}
* @param days {number}
*/
function addDaysToDate(d, days) {
var oneDayInMilliseconds = 86400000;
return new Date(d.getTime() + (oneDayInMilliseconds * days));
}
And to format the date without moment.js:
/**
* formatDate
* returns a string with date parameters replaced with the date objects corresponding values
* @param d {Date}
* @param format {string}
*/
function formatDate(d, format) {
if (format === void 0) { format = "!d!/!m!/!y!"; }
return format
.replace(/!y!/ig, d.getFullYear().toString())
.replace(/!m!/ig, (d.getMonth() + 1).toString())
.replace(/!d!/ig, d.getDate().toString());
}
//Testing
var d = new Date();
console.log("d/m/y:", formatDate(d, "!d!/!m!/!y!"));
console.log("m/d/y:", formatDate(d, "!m!/!d!/!y!"));
console.log("It was the d of m, y:", formatDate(d, "It was the !d! of !m!, !y!"));