简体   繁体   中英

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

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?

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');

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM