javascript – 如何用moment.js减去2次,然后减去几分钟

我需要用moment.js减去2次(得到差异),然后用这个结果减去一些额外的分钟(简单的int).它用于计算时间表.几个例子:

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"

我知道moment.js可以做到这一点,但我很难获得预期的结果.我一直在尝试这个:

function getTimeInterval(startTime, endTime){
        return moment(moment(startTime,"hh:mm").diff(moment(endTime,"hh:mm"))).format("hh:mm"); 
}

格式似乎正确,但我得到的值不正确.例如,我的示例#2返回的结果是“6:30”而不是“10:30”然后我如何减去午餐的int分钟?

任何帮助深表感谢.

最佳答案
// 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');

密切关注格式的外壳.你正在使用这是一个12小时的时钟.

另见:Get the time difference between two datetimes

转载注明原文:javascript – 如何用moment.js减去2次,然后减去几分钟 - 代码日志