Check if weekend exist in date range using javascript

前端 未结 7 1822
我在风中等你
我在风中等你 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:01

    Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):

    function containsWeekend(d1, d2)
    {
        // note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
        // you might want to add code to check those conditions
        var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
        if (interval > 5) {
            return true;    // must contain a weekend day
        }
        var day1 = d1.getDay();
        var day2 = d2.getDay();
        return !(day1 > 0 && day2 < 6 && day2 > day1);
    }
    

    fiddle

    If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.

提交回复
热议问题