当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何用moment.js减去2次,然后减去几分钟》经验,为你挑选了1个好方法。

我需要用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分钟?

任何帮助深表感谢.



1> Matt Johnson..:
// 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');

密切关注格式的外壳.您使用的hh是12小时制.

另请参阅: 获取两个日期时间之间的时差

推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有