首页 文章

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

提问于
浏览
0

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

    如果您在JavaScript中查看Date对象及其方法和属性,您会发现JavaScript自1970年以来的时间基于毫秒 .

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

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

相关问题