10

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158

2 Answers2

36
// 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

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
3

You can use the diff method to calculate the difference between two dates and the subtract method to subtract time. In your case:

function getTimeInterval(startTime, endTime, lunchTime){
    var start = moment(startTime, "HH:mm");
    var end = moment(endTime, "HH:mm");
    var minutes = end.diff(start, 'minutes');
    var interval = moment().hour(0).minute(minutes);
    interval.subtract(lunchTime, 'minutes');
    return interval.format("HH:mm");
}
VincenzoC
  • 30,117
  • 12
  • 90
  • 112