You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已实现周末排除天数统计,如何用jQuery获取对应所有日期?

Solution: Get List of Business Days (Excluding Weekends) Between Two Dates

Got it, so you already have a function that counts business days, but you need to pull the actual list of those dates instead of just the count. Let's build a straightforward, easy-to-maintain solution using JavaScript (works seamlessly in jQuery environments):

Implementation Code

function getBusinessDates(startDate, endDate) {
  const businessDates = [];
  // Create a copy of the start date to avoid modifying the original input
  const currentDate = new Date(startDate);

  // Loop through each day from start to end date
  while (currentDate <= endDate) {
    const dayOfWeek = currentDate.getDay();
    // Exclude Sunday (0) and Saturday (6)
    if (dayOfWeek !== 0 && dayOfWeek !== 6) {
      // Push a copy of the current date to prevent reference issues
      businessDates.push(new Date(currentDate));
    }
    // Move to the next day
    currentDate.setDate(currentDate.getDate() + 1);
  }

  return businessDates;
}

Key Details to Note

  • Date Object Copies: Since Date is a reference type, we create fresh copies when adding to the array. This prevents later modifications to currentDate from altering dates already stored in the list.
  • Weekday Check: getDay() returns 0 for Sunday and 6 for Saturday—we skip these and keep days 1-5 (Monday to Friday).
  • Inclusive Range: The loop runs as long as currentDate is less than or equal to endDate, so the end date is included if it's a weekday.

Example Usage

Let's test your sample scenario: Friday to Monday

// Define start (Fri, May 17 2024) and end (Mon, May 20 2024) dates
// Note: Months are 0-indexed in JavaScript Date
const start = new Date(2024, 4, 17);
const end = new Date(2024, 4, 20);

// Get the list of business dates
const dates = getBusinessDates(start, end);

// Print formatted dates (e.g., YYYY-MM-DD)
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

dates.forEach(date => console.log(formatDate(date)));
// Output:
// 2024-05-17
// 2024-05-20

This approach is more intuitive than reverse-engineering dates from a count, and it's easy to extend later—for example, if you need to exclude holidays, you can just add an extra check in the loop.

内容的提问来源于stack exchange,提问作者Vishal Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:11:40