Check if weekend exist in date range using javascript

前端 未结 7 1821
我在风中等你
我在风中等你 2021-01-12 21:27

Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.

var date1 = \'Apr 10, 2014\';
var date2 = \'Apr 14, 2014\         


        
相关标签:
7条回答
  • 2021-01-12 22:03

    Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)

    Demo: http://jsfiddle.net/abhitalks/xtD5V/1/

    Code:

    function isWeekend(date1, date2) {
        var d1 = new Date(date1),
            d2 = new Date(date2), 
            isWeekend = false;
    
        while (d1 < d2) {
            var day = d1.getDay();
            isWeekend = (day === 6) || (day === 0); 
            if (isWeekend) { return true; } // return immediately if weekend found
            d1.setDate(d1.getDate() + 1);
        }
        return false;
    }
    

    If you want to check if the whole weekend exists between the two dates, then change the code slightly:

    Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/

    Code:

    function isFullWeekend(date1, date2) {
        var d1 = new Date(date1),
            d2 = new Date(date2); 
    
        while (d1 < d2) {
            var day = d1.getDay();
            if ((day === 6) || (day === 0)) { 
                var nextDate = d1; // if one weekend is found, check the next date
                nextDate.setDate(d1.getDate() + 1); // set the next date
                var nextDay = nextDate.getDay(); // get the next day
                if ((nextDay === 6) || (nextDay === 0)) {
                    return true; // if next day is also a weekend, return true
                }
            }
            d1.setDate(d1.getDate() + 1);
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题