Her*_*der 7 javascript momentjs
我需要用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"
Run Code Online (Sandbox Code Playgroud)
我知道moment.js可以做到这一点,但我很难获得预期的结果.我一直在尝试这个:
function getTimeInterval(startTime, endTime){
return moment(moment(startTime,"hh:mm").diff(moment(endTime,"hh:mm"))).format("hh:mm");
}
Run Code Online (Sandbox Code Playgroud)
格式似乎正确,但我得到的值不正确.例如,我的示例#2返回的结果是"6:30"而不是"10:30" 然后我如何减去午餐的int分钟?
任何帮助深表感谢.
Mat*_*int 30
// 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');
Run Code Online (Sandbox Code Playgroud)
密切关注格式的外壳.您使用的hh是12小时制.
另请参阅: 获取两个日期时间之间的时差
| 归档时间: |
|
| 查看次数: |
26081 次 |
| 最近记录: |