我有一个检查当前时间是否在工作时间内的功能-目前,我仅使用布尔函数检查工作时间,夏令时和周末。
如何设置假期日期列表,并具有功能来检查今天的当前日期是否是假期,如果不是,则返回true,否则返回false。
最好的方法是创建一个日期数组, 这样吗?
var holidays = { // keys are formatted as month,day
"0,1": "Martin Luther King, Jr. Day",
"1,1": "President's Day",
"2,0": "Daylight Savings Time Begins",
"3,3": "Administrative Professionals Day",
"4,0": "Mother's Day",
"4,1": "Memorial Day",
"5,0": "Father's Day",
"6,0": "Parents Day",
"8,1": "Labor Day",
"8,0": "Gold Star Mothers Day",
"9,1": "Columbus Day",
"10,0": "Daylight Savings Time Ends",
"10,4": "Thanksgiving Day"
};
//or like this?
var holidays = ["Martin Luther King, Jr. Day": {
"day":"1",
"month":"0"
},
"President's Day": {
"day":"1",
"month":"1"
}];
然后检查是否 date.getMonth() date.getDate()
等于列表中的一项,然后返回true,否则返回false
这样的作品行吗?
function checkHoliday(){
month = date.getMonth()
date = date.getDate()
for (var i=0; i < holidays.length ;i++){
if(holidays[i].day == date && holidays[i].month == month) {
return true
} else return false;
}
答案 0 :(得分:3)
示例
function checkHoliday(){
var month = date.getMonth();
var date = date.getDate();
return holidays.hasOwnProperty(month + ',' + date);
}
答案 1 :(得分:1)
我会做这样的事情:
const holidays = [
{name: 'Martin Luther King, Jr. Day', day: 20, month: 1},
{name: 'Presidents Day', day: 17, month: 2}
];
function checkHoliday(){
const today = new Date(); // get date of today
for(var i = 0; i < holidays.length; i++){
let isHoliday = holidays[i].day === today.getDate() && holidays[i].month === today.getMonth() + 1; // check if today is a holiday
if(isHoliday) return true; // return true if today is a holiday
// you could also return which holiday it is using: if(isHoliday) return holidays[i].name;
}
return false; // else return false
}
console.log(checkHoliday());
但是,我认为对此的怀念比我的想法更好。只有一件事:
如果有,您可以返回假日名称而不是true 当天没有假期,它将返回undefined。
const holidays = {
"0,1": "Martin Luther King, Jr. Day",
"1,1": "President's Day",
"2,0": "Daylight Savings Time Begins",
"3,3": "Administrative Professionals Day",
"4,0": "Mother's Day",
"4,1": "Memorial Day",
"5,0": "Father's Day",
"6,0": "Parents Day",
"8,1": "Labor Day",
"8,0": "Gold Star Mothers Day",
"9,1": "Columbus Day",
"10,0": "Daylight Savings Time Ends",
"10,4": "Thanksgiving Day"
};
let date = new Date();
function checkHoliday() {
const month = date.getMonth();
const day = date.getDate();
return holidays[month + ',' + day];
}
// As you can see, this could also be used like a boolean:
if(checkHoliday()) console.log('true because the function returns:', checkHoliday());
else console.log('false because the function returns:', checkHoliday());
// The following is only to fake a holiday:
document.getElementById('makeHoliday').onclick = () => {
date = new Date(2019, 0, 1);
if(checkHoliday()) console.log('true because the function returns:', checkHoliday());
else console.log('false because the function returns:', checkHoliday());
}
<button id="makeHoliday">Klick here to fake a holiday</button>