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
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
It's the simpliest way to count difference in one day:
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.moment constructor defaults to current year, month and day, so your problem is that
end
is beforestart
. You can compare your variables usingisBefore
and then useadd
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 theformat
method).Here a working sample: