我如何计算一周的总和?
我有一个类似这样的校园文件,
{
"_id" : ObjectId("5ce3beecf32c6e5ba2d767e8"),
"managers" : [
ObjectId("5cd2a3de1e2d5928b04321b9"),
ObjectId("5cd2a34e1e2d5928b04321b7")
],
"admins" : [
ObjectId("5cd3b1d0877c5b07921932dd")
],
"status" : true,
"name" : "Halliday Hall",
"address1" : "Oliver Rd",
"address2" : "Thunder Bay",
"city" : "Ontario",
"state" : "Ontario",
"postCode" : "8465",
"email" : "halliday@gmail.com",
"phone" : 8475963269.0,
"workingDays" : {
"Sunday" : [
"Closed",
"Closed"
],
"Monday" : [
"10:30 AM",
"04:30 PM"
],
"Tuesday" : [
"10:00 AM",
"05:00 PM"
],
"Wednesday" : [
"Closed",
"Closed"
],
"Thursday" : [
"Closed",
"Closed"
],
"Friday" : [
"Closed",
"Closed"
],
"Saturday" : [
"Closed",
"Closed"
]
}
}
wokingDays是地图类型
workingDays: {
type: Map,
of: Array
}
我要做的就是计算工时总数
我尝试使用一下矩,但被查询卡住了。
在这种情况下,预期总和为13小时。
答案 0 :(得分:2)
我已经计算了开始时间和结束时间,并使用矩来减去时间,然后将其转换为小时,我们可以在迭代器中使用此逻辑来找出差异。
const startTime=moment("10:30 AM", "HH:mm a"),
endTime=moment("04:30 PM", "HH:mm a"),
duration = moment.duration(endTime.diff(startTime)),
hours = parseInt(duration.asHours());
console.log(`No of hours = ${hours}`);
请在下面的代码中进行迭代,找出一周中的小时数,
const moment = require('moment');
const req_object = {
"_id" : "5ce3beecf32c6e5ba2d767e8",
"workingDays" : {
"Sunday" : [
"Closed",
"Closed"
],
"Monday" : [
"10:30 AM",
"04:30 PM"
],
"Tuesday" : [
"10:00 AM",
"05:00 PM"
],
"Wednesday" : [
"Closed",
"Closed"
],
"Thursday" : [
"Closed",
"Closed"
],
"Friday" : [
"Closed",
"Closed"
],
"Saturday" : [
"Closed",
"Closed"
]
}
}
let wd = req_object.workingDays;
let hours = 0;
for (var item in wd) {
if (wd[item][0] != "Closed") {
const startTime=moment(wd[item][0], "HH:mm a"),
endTime=moment(wd[item][1], "HH:mm a"),
duration = moment.duration(endTime.diff(startTime));
hours += parseInt(duration.asHours());
}
}
console.log(`No of hours = ${hours}`);
请回复,它对您有用吗?