已实现周末排除天数统计,如何用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
Dateis a reference type, we create fresh copies when adding to the array. This prevents later modifications tocurrentDatefrom altering dates already stored in the list. - Weekday Check:
getDay()returns0for Sunday and6for Saturday—we skip these and keep days 1-5 (Monday to Friday). - Inclusive Range: The loop runs as long as
currentDateis less than or equal toendDate, 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
相关产品推荐
相关产品推荐

