由於項目開發中遇到須要向後臺傳本週的開始和結束時間,以及上一週的起止時間,就琢磨了半天,總算寫出來一套,寫篇文章是爲了方便本身記憶,也是分享給須要的人,水平有限,寫的很差請見諒:數組
getDateStr3函數是爲了把時間對象轉變爲yy-mm-dd的字符串,方便傳值;函數
getWeekStartAndEnd函數是獲取周的起止時間,而且用getDateStr3轉換成字符串放到數組中,其中參數0表明當前周,-1表明前一週,-2表明上上週,以此類推,反過來也能夠1表明下一週;code
getMonthStartAndEnd函數是獲取月的起止時間,傳參同上對象
//獲取當前日期yy-mm-dd //date 爲時間對象 function getDateStr3(date) { var year = ""; var month = ""; var day = ""; var now = date; year = ""+now.getFullYear(); if((now.getMonth()+1)<10){ month = "0"+(now.getMonth()+1); }else{ month = ""+(now.getMonth()+1); } if((now.getDate())<10){ day = "0"+(now.getDate()); }else{ day = ""+(now.getDate()); } return year+"-"+month+"-"+day; } /** * 得到相對當前周AddWeekCount個周的起止日期 * AddWeekCount爲0表明當前周 爲-1表明上一個周 爲1表明下一個周以此類推 * **/ function getWeekStartAndEnd(AddWeekCount) { //起止日期數組 var startStop = new Array(); //一天的毫秒數 var millisecond = 1000 * 60 * 60 * 24; //獲取當前時間 var currentDate = new Date(); //相對於當前日期AddWeekCount個周的日期 currentDate = new Date(currentDate.getTime() + (millisecond * 7*AddWeekCount)); //返回date是一週中的某一天 var week = currentDate.getDay(); //返回date是一個月中的某一天 var month = currentDate.getDate(); //減去的天數 var minusDay = week != 0 ? week - 1 : 6; //得到當前周的第一天 var currentWeekFirstDay = new Date(currentDate.getTime() - (millisecond * minusDay)); //得到當前周的最後一天 var currentWeekLastDay = new Date(currentWeekFirstDay.getTime() + (millisecond * 6)); //添加至數組 startStop.push(getDateStr3(currentWeekFirstDay)); startStop.push(getDateStr3(currentWeekLastDay)); return startStop; } /** * 得到相對當月AddMonthCount個月的起止日期 * AddMonthCount爲0 表明當月 爲-1表明上一個月 爲1表明下一個月 以此類推 * ***/ function getMonthStartAndEnd(AddMonthCount) { //起止日期數組 var startStop = new Array(); //獲取當前時間 var currentDate = new Date(); var month=currentDate.getMonth()+AddMonthCount; if(month<0){ var n = parseInt((-month)/12); month += n*12; currentDate.setFullYear(currentDate.getFullYear()-n); } currentDate = new Date(currentDate.setMonth(month)); //得到當前月份0-11 var currentMonth = currentDate.getMonth(); //得到當前年份4位年 var currentYear = currentDate.getFullYear(); //得到上一個月的第一天 var currentMonthFirstDay = new Date(currentYear, currentMonth,1); //得到上一月的最後一天 var currentMonthLastDay = new Date(currentYear, currentMonth+1, 0); //添加至數組 startStop.push(getDateStr3(currentMonthFirstDay)); startStop.push(getDateStr3(currentMonthLastDay)); //返回 return startStop; }