Moment.js以dd:hh:mm:ss格式获取两个日期之间的差异?

时间:2015-02-22 11:08:15

标签: javascript date momentjs

我正计算当天晚上11:59的时间。这是一个例子。

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.js"></script>
<script>

    setInterval(function() {

        var now = moment();
        var mid = moment();
        mid = mid.endOf('day');

        var diffHours = mid.diff(now, 'hours');
        var diffMinutes = mid.diff(now, 'minutes');
        var diffSeconds = mid.diff(now, 'seconds');

        console.log(diffHours + "h " + diffMinutes + "m " + diffSeconds + "s");

    }, 1000)

</script>

然而,我希望它会给我一个时间,例如20h 13m 49s,而不是20h 1255m 73500s

我知道这很有意义,但我怎样才能达到我想要的格式?

2 个答案:

答案 0 :(得分:5)

您需要在每个now之后修改diff变量。

var hours = mid.diff(now, 'hours'); //Get hours 'till end of day
now.hours(now.hours() + hours);
var minutes = mid.diff(now, 'minutes');

答案 1 :(得分:0)

为了比较,这里是大卫·普拉瑟的时刻。来自另一个答案的评论示例给出时间直到23:59:59.999“今天”和普通JS中的相同功能:

// Moment.js version
var now = moment();
var mid = moment();
mid = mid.endOf('day');
var diff1 = moment.utc(moment(mid, "DD/MM/YYYY HH:mm:ss")
             .diff(moment(now, "DD/MM/YYYY HH:mm:ss")))
           .format("HH:mm:ss");

console.log('moment.js: ' + diff1);

// POJS version
var z = (n) => (n<10? '0' : '') + n;
var ms = new Date().setHours(23,59,59,999) - new Date();
var diff2 = z(ms/3.6e6|0) + ':' +
            z(ms%3.6e6/6e4|0) + ':' +
            z(ms%6e4/1e3|0);

console.log('plain js : ' + diff2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>