Count duration between two times after midnight

前端 未结 3 1881
逝去的感伤
逝去的感伤 2021-01-14 12:58

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)).a         


        
相关标签:
3条回答
  • 2021-01-14 13:31

    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;
    
    0 讨论(0)
  • 2021-01-14 13:39

    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>

    0 讨论(0)
  • 2021-01-14 13:42

    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>

    0 讨论(0)
提交回复
热议问题