欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JS计算工作日

程序员文章站 2022-05-17 21:02:12
...

 

function stringToDate(dateString){ 
    dateString = dateString.split('-'); 
    return new Date(dateString[0], dateString[1] - 1, dateString[2]); 
}

 

function countWorkDay(date1, date2){
        date1 = stringToDate(date1);
        date2 = stringToDate(date2);
        delta = (date2 - date1) / (1000 * 60 * 60 * 24) + 1; // 计算出总时间

        weeks = 0;
        for(i = 0; i < delta; i++){
            if(date1.getDay() == 0 || date1.getDay() == 6) weeks ++;  // 若为周六或周天则加1
            date1 = date1.valueOf();
            date1 += 1000 * 60 * 60 * 24;
            date1 = new Date(date1);
        }
        return delta - weeks;
    }
    console.log(countWorkDay('2017-08-01','2017-08-06'));  // 4

作者:黄清淮
链接:https://www.jianshu.com/p/f5c43596d57a

转载:https://www.jianshu.com/p/f5c43596d57a