I need to subtract 2 times with moment.js (get the difference), and then with that result, subtract some additional minutes (simple int). It's for calculating timesheets. A few examples:
Example #1:
Start time: 10:00 AM (represented in js as "10:00")
End time: 2:00 PM (represented in js as "14:00")
Lunch: 30 minutes ("30")
Expected result: "3:30" (10am - 2pm is 4 hours, minus 30 minutes for lunch = 3hrs 30 mins -- and I need it output as "3:30")
Example #2:
Start time: 6:15 AM (represented in js as "6:15")
End time: 4:45 PM (represented in js as "16:45")
Lunch: 0 minutes ("0")
Expected result: "10:30"
I know moment.js can do this but I'm struggling to get expected results. I've been trying this:
function getTimeInterval(startTime, endTime){
return moment(moment(startTime,"hh:mm").diff(moment(endTime,"hh:mm"))).format("hh:mm");
}
The formatting seems right, but I'm getting incorrect values. For example, the result returned for my example #2 is "6:30" instead of "10:30" And then how do I subtract off int minutes for lunch?
Any help is much appreciated.
// parse time using 24-hour clock and use UTC to prevent DST issues
var start = moment.utc(startTime, "HH:mm");
var end = moment.utc(endTime, "HH:mm");
// account for crossing over to midnight the next day
if (end.isBefore(start)) end.add(1, 'day');
// calculate the duration
var d = moment.duration(end.diff(start));
// subtract the lunch break
d.subtract(30, 'minutes');
// format a string result
var s = moment.utc(+d).format('H:mm');
Pay close attention to the casing of the formats. You were using hh
which is for a 12-hour clock.
See also: Get the time difference between two datetimes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With