Moment.js Get difference between two dates in the dd:hh:mm:ss format?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-14 14:57:13

问题


I am calculating the time until 11:59PM of the current day. Here is an example.

<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>

However, I was hoping it would show me a time such as 20h 13m 49s, instead I am getting 20h 1255m 73500s

I understand this is working as intended pretty much, but how can I achieve the format I am seeking?


回答1:


You'll want to modify your now variable after each diff.

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



回答2:


Just for comparison, here's David Stampher's moment.js example from a comment on another answer giving the time until 23:59:59.999 "today" and the same functionality in plain 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>


来源:https://stackoverflow.com/questions/28657113/moment-js-get-difference-between-two-dates-in-the-ddhhmmss-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!