exclude weekends in javascript date calculation

前端 未结 4 573
甜味超标
甜味超标 2020-11-28 16:22

I have two sets of codes that work. Needed help combining them into one.

This code gets me the difference between two dates. works perfectly:

functio         


        
4条回答
  •  借酒劲吻你
    2020-11-28 17:19

    Here's a simple function to calculate the number of business days between two date objects. As designed, it does not count the start day, but does count the end day so if you give it a date on a Tuesday of one week and a Tuesday of the next week, it will return 5 business days. This does not account for holidays, but does work properly across daylight savings changes.

    function calcBusinessDays(start, end) {
        // This makes no effort to account for holidays
        // Counts end day, does not count start day
    
        // make copies we can normalize without changing passed in objects    
        var start = new Date(start);
        var end = new Date(end);
    
        // initial total
        var totalBusinessDays = 0;
    
        // normalize both start and end to beginning of the day
        start.setHours(0,0,0,0);
        end.setHours(0,0,0,0);
    
        var current = new Date(start);
        current.setDate(current.getDate() + 1);
        var day;
        // loop through each day, checking
        while (current <= end) {
            day = current.getDay();
            if (day >= 1 && day <= 5) {
                ++totalBusinessDays;
            }
            current.setDate(current.getDate() + 1);
        }
        return totalBusinessDays;
    }
    

    And, the jQuery + jQueryUI code for a demo:

    // make both input fields into date pickers
    $("#startDate, #endDate").datepicker();
    
    // process click to calculate the difference between the two days
    $("#calc").click(function(e) {
        var diff = calcBusinessDays(
            $("#startDate").datepicker("getDate"), 
            $("#endDate").datepicker("getDate")
        );
        $("#diff").html(diff);
    });
    

    And, here's a simple demo built with the date picker in jQueryUI: http://jsfiddle.net/jfriend00/z1txs10d/

提交回复
热议问题