近期在作數據報表,時間處理部分很是繁瑣,其中一個需求是給定一個時間須要獲取該時間所在周的週一及週末,下面是代碼:spa
//調用,不傳時間就默認爲今天 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; }