Sunday, December 27, 2015

Count number of weekends between two dates using JavaScript

Simple function to calculate number of weekends in-between from and to dates

/********************************************************************************
   * Function : getWeekend                                                                                                                     *
   * Descritption :This function is used to return the number of weekends in-between form and to Dates*   ********************************************************************************/
function getWeekend(dString1, dString2) {
    var aDay = 24 * 60 * 60 * 1000;
    var d1 = new Date(Date.parse(dString1)); //"MM/DD/YYYY"
    var d2 = new Date(Date.parse(dString2));
    var weekend = {
        Sat: 0,
        Sun: 0
    }
    for (var d, i = d1.getTime(), n = d2.getTime() ; i <= n; i += aDay) {
        d = new Date(i).getDay();
        if (d === 6) weekend.Sat++;
        if (d === 0) weekend.Sun++;
    }
    return weekend.Sat + weekend.Sun;
}

No comments:

Post a Comment