Count duration between two times after midnight

2019-02-19 05:31发布

问题:

How to count duration between two times?

var start = moment('17:00', "HH:mm");
var end = moment('02:15', "HH:mm");
moment.duration(end.diff(start)).asHours()
//outputs  -14.75 instead of 9.15

回答1:

moment constructor defaults to current year, month and day, so your problem is that end is before start. You can compare your variables using isBefore and then use add to "trasform" end to the next day.

Note that asHours gives fractional values (so you'll have 9.25 instead of 9.15). If you need to get "9 hours and 15 minutes" you can use moment-duration-format plug-in (for example you caun use 'h[.]m' as template in the format method).

Here a working sample:

var start = moment('17:00', "HH:mm");
var end = moment('02:15', "HH:mm");
if( end.isBefore(start) ){
  end.add(1, 'day');
}
var dur = moment.duration(end.diff(start))
var result = dur.asHours();
document.writeln(result);
document.write(dur.format('h[.]m'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>



回答2:

It's the simpliest way to count difference in one day:

var start = moment('17:00', "HH:mm");
var end = moment('02:15', "HH:mm");
var duration = moment.duration(end.diff(start)).asHours();
if (duration < 0) duration += 24;


回答3:

I think the problem is that you have 2 moment objects, one representing today 17:00 and one today 02:15. Though you want today 17:00 and tomorrow 02:15. Just use moment('02:15', "HH:mm").add(1, 'days') to get the next day.

var start = moment('17:00', "HH:mm");
var end = moment('02:15', "HH:mm").add(1, "days");
var result = moment.duration(end.diff(start)).asHours();
document.write(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>