/**
* 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));
}
并在没有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!"));
1 回答
如果您在JavaScript中查看Date对象及其方法和属性,您会发现JavaScript自1970年以来的时间基于毫秒 .
知道您可以通过添加或减去毫秒来轻松修改日期 .
并在没有moment.js的情况下格式化日期: