我有这个脚本,它将今天的日期与多个日期范围进行比较。 它按原样工作,但我想知道它是否足够强大,或者它是否可以更好地完成 - 特别是当日期字符串转换为日期对象时的部分。可以更聪明地完成吗?
具有日期范围的数组必须是可读字符串,因为它们由非技术人员维护。
Js:
//An array of objects containing date ranges
var datesArray = [{
"from": "2/12/2016",
"to": "8/12/2016",
"schedule": "Opening hours: 9-5"
}, {
"from": "11/10/2017",
"to": "16/10/2017",
"schedule": "Opening hours: 9-7"
}, {
"from": "17/10/2017",
"to": "22/10/2017",
"schedule": "Closed"
}];
// Today's date
var today = new Date();
// Set a flag to be used when found
var found = false;
// For each calendar date, check if it is within a range.
for (i = 0; i < datesArray.length; i++) {
// Get each from/to ranges
var From = datesArray[i].from.split("/");
var To = datesArray[i].to.split("/");
// Format them as dates : Year, Month (zero-based), Date
var FromDate = new Date(From[2], From[1] - 1, From[0]);
var ToDate = new Date(To[2], To[1] - 1, To[0]);
var schedule = datesArray[i].schedule;
// Compare date
if (today >= FromDate && today <= ToDate) {
found = true;
$("#dates").html(schedule);
break;
}
}
//At the end of the for loop, if the date wasn't found, return true.
if (!found) {
console.log("Not found");
}
答案 0 :(得分:1)
选中https://sarthak-port.000webhostapp.com/Mportfolio.html。
我已将dateformat更改为mm / dd / yyyy,并通过'/'位删除了拆分。代码如下:
#container {
align-items: center;
display: flex;
}
.small {
background: #fcc;
}
.big {
background: #ccf;
font-size: 2em;
}