我有这个脚本,它比较今天的日期和多个日期范围。它可以正常工作,但是我想知道它是否足够健壮,或者它是否可以做得更好--特别是当日期字符串转换成日期对象时。能做得更聪明吗?
具有日期范围的数组必须是可读字符串,因为它们是由非技术人员维护的。
联署材料:
//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");
}发布于 2017-10-15 09:35:37
看看这个小提琴。
我已将您的日期格式更改为mm/dd/yyyy,并删除了“/”位的拆分。守则如下:
// An array of objects containing date ranges
var datesArray = [{
"from": "12/2/2016",
"to": "12/8/2016",
"schedule": "Opening hours: 9-5"
}, {
"from": "10/11/2017",
"to": "10/16/2017",
"schedule": "Opening hours: 9-7"
}, {
"from": "10/17/2017",
"to": "10/22/2017",
"schedule": "Closed"
}];
// Today's date
var today = Date.parse(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 = Date.parse(datesArray[i].from);
var To = Date.parse(datesArray[i].to);
// Format them as dates : Year, Month (zero-based), Date
var schedule = datesArray[i].schedule;
console.log(From+'>>'+To);
// Compare date
if (today >= From && today <= To) {
found = true;
console.log("Opening hours: " + schedule);
$("#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");
}https://stackoverflow.com/questions/46753487
复制相似问题