给定一个时间,获取该时间所在周的周一及周日

近期在做数据报表,时间处理部分非常繁琐,其中一个需求是给定一个时间需要获取该时间所在周的周一及周末,下面是代码:

//调用,不传时间就默认为今天
console.log(getWeek('2017-11-08'));
//给定一个时间获取本周的星期一及星期日
    function getWeek(time){
        var now='';
        time?(now = new Date(time)):(now = new Date());
        var day = now.getDay();
        if(day == 0){
            day = 7;
        }
        var nowTime = now.getTime(),
            MondayTime = nowTime - (day-1)*24*60*60*1000,    // 周一
            SundayTime =  nowTime + (7-day)*24*60*60*1000;   // 周日var monday = new Date(MondayTime),                   // 格式化周一
            start_Year =monday.getFullYear(),
            start_Month = monday.getMonth()+ 1,
            start_Day = monday.getDate();
        var sunday = new Date(SundayTime),                   // 格式化周末
            end_Year =sunday.getFullYear(),
            end_Month = sunday.getMonth()+ 1,
            end_Day = sunday.getDate();
        if(start_Month<10) {
            start_Month="0"+start_Month;
        }
        if(start_Day < 10) {
            start_Day="0"+start_Day;
        }
        if(end_Month<10) {
            end_Month="0"+end_Month;
        }
        if(end_Day < 10) {
            end_Day="0"+end_Day;
        }
        var start_time = start_Year+'-'+start_Month+'-'+start_Day;
        var end_time = end_Year+'-'+end_Month+'-'+end_Day;
        if(new Date()<new Date(end_time)){
            var today = new Date().toLocaleDateString().replace(/\//g, "-");
            var today_year = today.substring(0,4);
            var today_month = today.substring(5,7);
            var today_day = today.substring(8,10);
            if(today_day<10) {
                today_day="0"+today_day;
            }
            end_time = today_year+'-'+today_month+'-'+today_day;
        }
        return start_time+' -- '+end_time;
    }
原文地址:https://www.cnblogs.com/huangtao5921/p/7802540.html