如何在Javascript中减去两个日期并将日期添加到特定日期

时间:2017-03-27 08:11:24

标签: javascript date datetime datetime-format

var date1 = 13/10/2016 04:35;

var date2 = 27/03/2017 08:00;

var diff = date2 - date1

如何减去上述格式的两个javascript日期,并知道它们之间的天数,并以DD /月/年格式返回结果。另外我想添加180天到date1并输出DD /月/年格式的结果?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

如果你看一下JavaScript中的Date对象及其方法和属性,你会发现自1970年以来JavaScript的时间基于毫秒。

知道您可以通过添加或减去毫秒来轻松修改日期。

/**
 * 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!"));