? ? ? ? 最近因公司業務需求需要實現一個按照每周的日期進行一些業務處理,需要獲取每個月有多少周,和每一周的開始日期到結束日期,經過一番思索,終于實現了,現在整理一下,方法如下:
getWeeksWithYearAndMonth(years,month){
var? weeks = [];//現將星期數組重制一次
? ? var month2 = parseInt(month)-1;
? ? var myDate =new Date(years,month2,1);//獲取每個月的第一天是星期幾
? ? var firstDay = myDate.getDay();
? ? alert(myDate.getDay());
? ? var myDate2 =new Date(years,month2,0);
? ? var days = myDate2.getDate();//獲取每個月有多少天
? ? alert(days);
? ? var firstMonday ='';
? ? var lastDay ='';
? ? if (firstDay-1==0){
????firstMonday = firstDay;//計算當月第一個星期一是幾號
? ? ? ? lastDay = days;//計算當月減去第一個不完整的星期天,剩余的天數
? ? }else {
????????firstMonday =7-firstDay+2;//計算當月第一個星期一是幾號
? ? ? ? lastDay = days-(7-firstDay+1);//計算當月減去第一個不完整的星期天,剩余的天數
? ? }
????var weeksCount = Math.floor(lastDay/7);//計算當月有幾個完整的星期天
? ? alert(weeksCount);
? ? var weekth ='';
? ? for (var i=0;i<weeksCount;i++){
????????weekth = i+1
? ? ? ? var week =new Object();
? ? ? ? week.label = month+'/'+(firstMonday+7*i)+'----'+month+'/'+((firstMonday+7*i)+7-1)+'(第'+weekth+'周)';
? ? ? ? week.value = (i+1).toString();
? ? ? ? weeks.push(week);
? ? }
var shengyuDays = lastDay%7;//計算當月最后一個不完整的星期天有幾天
? ? if (shengyuDays>0){//如果一個月的最后一個不完整的星期天天數大于零,則順延到下一個月
? ? ? ? var week =new Object();
? ? ? ? var lastMoth ='';
? ? ? ? if (parseInt(month)==12){//如果當前月份為12月,則下一個月為1月
? ? ? ? ? ? lastMoth ='01';//下一年的1月
? ? ? ? }else {
lastMoth =parseInt(month)+1;//下一個月
? ? ? ? }
var lastWeekCount =7-shengyuDays;
? ? ? ? week.label = month+'/'+(firstMonday+7*weeksCount)+'----'+'0'+lastMoth.toString()+'/'+lastWeekCount+'(第'+(weeksCount+1)+'周)';
? ? ? ? week.value = (weeksCount+1).toString();
? ? ? ? weeks.push(week);
? ? }
????return weeks;
}