Determines whether a given date range contains the specified day of the week

I encountered a requirement in the project to determine whether a given date range contains the specified day of the week.

    function checkWeekdayInRange(startDate, endDate, weekday) {
    
    
      const start = new Date(startDate);
      const end = new Date(endDate);

      // 将开始日期设置为0点
      start.setHours(0, 0, 0, 0);

      // 将结束日期设置为23:59:59.999
      end.setHours(23, 59, 59, 999);

      // 循环遍历日期范围内的每一天,检查该天是否是指定的星期几
      for (let d = start; d <= end; d.setDate(d.getDate() + 1)) {
    
    
        if (d.getDay() === weekday) {
    
    
          return true;
        }
      }

      // 如果循环结束仍未找到指定的星期几,则返回 false
      return false;
    }

This function accepts three parameters:

  • startDate: The start date of the range. Must be a legal date string (such as "2023-04-22") or a Unix timestamp (an integer in milliseconds).
  • endDate: The end date of the range. Must have the same format as startDate.
  • weekday: The day of the week to be found. Must be an integer from 0 (Sunday) to 6 (Saturday).

The function first converts startDate and endDate to Date type, and sets the time part of startDate to 0 o'clock and the time part of endDate to 23:59:59.999. This ensures that the date range covers all time points.

The function then uses a loop to iterate through each day in the range and uses the getDay() method to get the day of the week for that day. Returns true if the specified day of the week is found. If the specified day of the week is not found at the end of the loop, false is returned.

For example, to check if the days from April 22, 2023 to April 28, 2023 contain Saturday (i.e. 6), you can call the function like this:

const result = checkWeekdayInRange("2023-04-22", "2023-04-28", 6);
console.log(result); // true

This example will output true because the given date range includes Saturday, April 22, 2023.

Guess you like

Origin blog.csdn.net/qq_41915137/article/details/112318002