NodeJS JS检查假期

flseospp  于 5个月前  发布在  Node.js
关注(0)|答案(4)|浏览(69)

我有呼叫中心,我用这个JS代码让消息在营业时间和营业时间/周末后,它显示一条消息说,是支持时间之外,我的问题是,我如何使这个代码工作也为假期?

exports.handler = async function(context, event, callback) {
  const moment = require('moment-timezone');
  var now = moment().tz('America/New_York');
  console.log('Current time-->'+now);
  console.log('current hours-->'+now.hour());
  
  let isWorkingHours = false;
  //let isWorkingHours = true; // testing
 
  const weekday = now.isoWeekday(); 
  console.log('weekday-->'+weekday);
  
  if (now.hour() >= 9 && now.hour() <= 17 && weekday <= 5) {
  //if (now.hour() >= 4 && now.hour() <= 20 && weekday <= 2) { // testing
      isWorkingHours = true;
      //Console.log('This is outside working hours');
    }
    callback(null, {
    isWorkingHours: isWorkingHours
    });
}

字符串

mzsu5hc0

mzsu5hc01#

我从别人在StackOverflow上的帖子中得到了这个假期检查器(我应该记录下这个链接,但我忘记了)。你可以浏览所有你感兴趣的日期来创建一个完整的假期列表,或者只是检查给定的日期是否是假期

function check_holiday (dt_date) {

    // check simple dates (month/date - no leading zeroes)
    var n_date = dt_date.getDate(),
        n_month = dt_date.getMonth() + 1;
    var s_date1 = n_month + '/' + n_date;
    
    if (   s_date1 == '1/1'   // New Year's Day
        || s_date1 == '6/14'  // Flag Day
        || s_date1 == '7/4'   // Independence Day
        || s_date1 == '11/11' // Veterans Day
        || s_date1 == '12/25' // Christmas Day
    ) return true;
    
    // weekday from beginning of the month (month/num/day)
    var n_wday = dt_date.getDay(),
        n_wnum = Math.floor((n_date - 1) / 7) + 1;
    var s_date2 = n_month + '/' + n_wnum + '/' + n_wday;
    
    if (   s_date2 == '1/3/1'  // Birthday of Martin Luther King, third Monday in January
        || s_date2 == '2/3/1'  // Washington's Birthday, third Monday in February
        || s_date2 == '5/3/6'  // Armed Forces Day, third Saturday in May
        || s_date2 == '9/1/1'  // Labor Day, first Monday in September
        || s_date2 == '10/2/1' // Columbus Day, second Monday in October
        || s_date2 == '11/4/4' // Thanksgiving Day, fourth Thursday in November
    ) return true;

    // weekday number from end of the month (month/num/day)
    var dt_temp = new Date (dt_date);
    dt_temp.setDate(1);
    dt_temp.setMonth(dt_temp.getMonth() + 1);
    dt_temp.setDate(dt_temp.getDate() - 1);
    n_wnum = Math.floor((dt_temp.getDate() - n_date - 1) / 7) + 1;
    var s_date3 = n_month + '/' + n_wnum + '/' + n_wday;
    
    if (   s_date3 == '5/1/1'  // Memorial Day, last Monday in May
    ) return true;

    // misc complex dates
    if (s_date1 == '1/20' && (((dt_date.getFullYear() - 1937) % 4) == 0) 
    // Inauguration Day, January 20th every four years, starting in 1937. 
    ) return true;
        
    if (n_month == 11 && n_date >= 2 && n_date < 9 && n_wday == 2
    // Election Day, Tuesday on or after November 2. 
    ) return true;
    
    return false;
}

字符串

t9eec4r0

t9eec4r02#

用于检查特定时刻是否在我们的工作时间之外的逻辑在if语句中。
我会根据假期或休息日的时间范围将其抽象到某种存储中,你可以用一个表或缓存来存储这些假期(你应该提前加载它们)。
这样,你就可以做这样的事情:
1.搜索是否有日期与当前日期匹配的假日(仅匹配日期而不匹配时间戳,您可以使用moment's isSame仅按日期检查)
1.如果有匹配项,则将isWorkingHours返回为false
要检查日期是否匹配,您可以使用此方法(无论当前时间如何,当您在日期级别进行比较时,它都会返回true):

console.log(moment('2021-05-10 14:00:00').isSame('2021-05-10', 'day'));

字符串

dl5txlt9

dl5txlt93#

以下是您可能需要检查的事项列表:

  • 周末
  • “静态日期”假期(例如:圣诞节)
  • “可变日期”假期(例如:复活节)
  • 时间(例如:您的办公室在8:00开门)
/* Function that checks if office is available at a specific date
 * @returns {boolean}
 */
function is_office_available (date = new Date()) {

  // weekends, or actually any other day of the week
  let day = date.getDay();
  if ( [0 /*sunday*/, 6 /*saturday*/].includes(day) ) return false;

  // "static date" holidays (formatted as 'DD/MM')
  let dd_mm = date.getDate() + '/' + (date.getMonth()+1);
  if ( ['24/12', '25/12'].includes(dd_mm) ) return false;

  // TODO: "variable date" holidays

  // specific times
  // this logic has to be extended a LOT if, for example, you have
  // the office open from 8:30 to 17:30 with a launch break from 12:00 to 13:00 on weekdays
  // and from 9:00 to 12:00 only on mondays
  let hh = date.getHours();
  if (9 < hh || hh > 17) return false;
  

  // if no test returned true then the office is going to be available on that date
  return true;

}

字符串
你可以简单地在if语句中调用这个函数。
“可变日期”假期有一个相当长的(和无聊的)实施做,这取决于你在你的国家办事处。

dba5bblo

dba5bblo4#

这就是我如何检查美国假期时,我需要与日期和时间周围的混乱。
首先,我创建了一个getToday()函数,所有其他函数都是从这个函数派生的。这使得它基于我所在的当前日期而动态变化。代码注解有点重,以确保我解释了每个函数中的逻辑。
我已经测试了所有11个功能,包括闰年支持。希望这对你有帮助。

function getToday() {
  return new Date();
}
// 1. New Year's Day - January 1st
function getNewYearsDay(today) {
  const year = today.getFullYear();
  return new Date(year, 0, 1); // January is month 0 in JavaScript
}
// 2. Martin Luther King Jr. Day - Third Monday in January
function getThirdMondayInJanuary(today) {
  const year = today.getFullYear();
  const januaryFirst = new Date(year, 0, 1); // January is month 0 in JavaScript
  let dayOfWeek = januaryFirst.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // Calculate how many days to add to get to the first Monday in January
  // If January 1st is a Monday (1), add 7, otherwise calculate the difference to the next Monday
  const daysToAdd = dayOfWeek === 1 ? 7 : (8 - dayOfWeek);
  // Calculate the third Monday
  const thirdMonday = new Date(year, 0, 1 + daysToAdd + 7); // Add 7 more days for the third Monday
  return thirdMonday;
}
// 3. Presidents' Day - Third Monday in February
function getThirdMondayInFebruary(today) {
  const year = today.getFullYear();
  const februaryFirst = new Date(year, 1, 1); // February is month 1 in JavaScript
  let dayOfWeek = februaryFirst.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // Calculate how many days to add to get to the first Monday in February
  // If February 1st is a Monday (1), add 14 (two weeks), otherwise calculate the difference to the next Monday and add 14
  const daysToAdd = dayOfWeek === 1 ? 14 : (8 - dayOfWeek) + 14;
  // Calculate the third Monday
  const thirdMonday = new Date(year, 1, 1 + daysToAdd);
  return thirdMonday;
}
// 4. Memorial Day - Last Monday in May
function getLastMondayInMay(today) {
  const year = today.getFullYear();
  const mayThirtyFirst = new Date(year, 4, 31); // May is month 4 in JavaScript
  let dayOfWeek = mayThirtyFirst.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // Calculate how many days to subtract to get to the last Monday in May
  // If May 31st is a Monday (1), subtract 0, otherwise calculate the difference to the previous Monday
  const daysToSubtract = dayOfWeek === 1 ? 0 : dayOfWeek - 1;
  // Calculate the last Monday
  const lastMonday = new Date(year, 4, 31 - daysToSubtract);
  return lastMonday;
}
// 5. Juneteenth - June 19th
function getJuneteenth(today) {
  const year = today.getFullYear();
  return new Date(year, 5, 19); // June is month 5 in JavaScript
}
// 6. Independence Day - July 4th
function getIndependenceDay(today) {
  const year = today.getFullYear();
  return new Date(year, 6, 4); // July is month 6 in JavaScript
}
// 6.1 Independence Day - Observed
function getIndependenceDayObserved(today) {
  const year = today.getFullYear();
  const independenceDay = new Date(year, 6, 4); // July is month 6 in JavaScript
  const dayOfWeek = independenceDay.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // If Independence Day falls on a Saturday, observe on Friday (July 3)
  if (dayOfWeek === 6) return new Date(year, 6, 3);
  // If Independence Day falls on a Sunday, observe on Monday (July 5)
  if (dayOfWeek === 0) return new Date(year, 6, 5);
  // Otherwise, return Independence Day on July 4
  return independenceDay;
}
// 7. Labor Day - First Monday in September
function getFirstMondayInSeptember(today) {
  const year = today.getFullYear();
  const septemberFirst = new Date(year, 8, 1); // September is month 8 in JavaScript
  let dayOfWeek = septemberFirst.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // Calculate how many days to add to get to the first Monday in September
  // If September 1st is already a Monday (1), add 0 days, otherwise calculate the difference to the next Monday
  const daysToAdd = dayOfWeek === 1 ? 0 : (8 - dayOfWeek) % 7;
  // Calculate the first Monday
  const firstMonday = new Date(year, 8, 1 + daysToAdd);
  return firstMonday;
}
// 8. Columbus Day - Second Monday in October
function getSecondMondayInOctober(today) {
  const year = today.getFullYear();
  const octoberFirst = new Date(year, 9, 1); // October is month 9 in JavaScript
  let dayOfWeek = octoberFirst.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // Calculate how many days to add to get to the first Monday in October
  // If October 1st is a Monday (1), add 7 days, otherwise calculate the difference to the next Monday
  const daysToAdd = dayOfWeek === 1 ? 7 : (8 - dayOfWeek);
  // Calculate the second Monday
  const secondMonday = new Date(year, 9, 1 + daysToAdd);
  return secondMonday;
}
// 9. Veterans Day - November 11th
function getVeteransDay(today) {
  const year = today.getFullYear();
  return new Date(year, 10, 11); // November is month 10 in JavaScript
}
// 9.1 Veterans Day - Observed
function getVeteransDayObserved(today) {
  const year = today.getFullYear();
  const veteransDay = new Date(year, 10, 11); // November is month 10 in JavaScript
  const dayOfWeek = veteransDay.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // If Veterans Day falls on a Saturday, observe on Friday (November 10)
  if (dayOfWeek === 6) return new Date(year, 10, 10);
  // If Veterans Day falls on a Sunday, observe on Monday (November 12)
  if (dayOfWeek === 0) return new Date(year, 10, 12);
  // Otherwise, return Veterans Day on November 11
  return veteransDay;
}
// 10. Thanksgiving Day - Fourth Thursday in November
function getFourthThursdayInNovember(today) {
  const year = today.getFullYear();
  const novemberFirst = new Date(year, 10, 1); // November is month 10 in JavaScript
  let dayOfWeek = novemberFirst.getDay(); // 0 is Sunday, 1 is Monday, etc.
  // Calculate how many days to add to get to the first Thursday in November
  // If November 1st is a Thursday (4), add 0, otherwise calculate the difference to the next Thursday
  const daysToAdd = dayOfWeek === 4 ? 0 : (11 - dayOfWeek) % 7;
  // Calculate the fourth Thursday
  const fourthThursday = new Date(year, 10, 1 + daysToAdd + 21);
  return fourthThursday;
}
// 11. Christmas Day - December 25th
function getChristmasDay(today) {
  const year = today.getFullYear();
  return new Date(year, 11, 25); // December is month 11 in JavaScript
}

// Example usage
const today = getToday();

console.log("Today is:", today.toLocaleDateString());
console.log("New Year's Day:", getNewYearsDay(today).toLocaleDateString());
console.log("Martin Luther King Jr. Day:", getThirdMondayInJanuary(today).toLocaleDateString());
console.log("Presidents' Day:", getThirdMondayInFebruary(today).toLocaleDateString());
console.log("Memorial Day:", getLastMondayInMay(today).toLocaleDateString());
console.log("Juneteenth:", getJuneteenth(today).toLocaleDateString());
console.log("Independence Day:", getIndependenceDay(today).toLocaleDateString());
console.log("Independence Day Observed:", getIndependenceDayObserved(today).toLocaleDateString());
console.log("Labor Day:", getFirstMondayInSeptember(today).toLocaleDateString());
console.log("Columbus Day:", getSecondMondayInOctober(today).toLocaleDateString());
console.log("Veterans Day:", getVeteransDay(today).toLocaleDateString());
console.log("Veterans Day Observed:", getVeteransDayObserved(today).toLocaleDateString());
console.log("Thanksgiving Day:", getFourthThursdayInNovember(today).toLocaleDateString());
console.log("Christmas Day:", getChristmasDay(today).toLocaleDateString());

字符串

相关问题