Fork me on GitHub

Js计算-当月每周有多少天

查看Demo

源代码如下:

  <script>

  //计算当月总天数
  function getCountDays() {
          var curDate = new Date();
          /* 获取当前月份 */
          var curMonth = curDate.getMonth();
         /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
         curDate.setMonth(curMonth + 1);
         /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
         curDate.setDate(0);
         /* 返回当月的天数 */
         return curDate.getDate();
  }

  //计算该月总周数
  function getWeekCounts( year, month ) {   
      var lastDay = new Date(year, month, 0).getDate();  //这个月的最后一天  --->(拿到这个月有多少天 )
      return Math.ceil(lastDay / 7);
  }  

  //第一周天数
  function getFirstWeek() {

      var month0 = new Date().getMonth();   //当前月所处月份
      var yeah0 = new Date().getFullYear();    //当前所处年

      var firstDate1 = new Date(yeah0, month0,1).toString('yyyy-MM-dd');    //该月的第一天的年月日。
      var first = new Date(firstDate1).getDay();       //该月第一天是周几   (日一二三四五六   ----对应数字:0、1、2、3、4、5、6)

      var endhao = 6;     // 周六
      var week1_day = endhao - first + 1;
      return week1_day;
  }

  //计算当月每周多少天
  function getWeekOfDay(){
    var month0 = new Date().getMonth()+1;   //当前月所处月份
    var yeah0 = new Date().getFullYear();    //当前所处年
    var weeks = getWeekCounts( yeah0, month0 );   //当前月的总周数
    var days = getCountDays();   //当前月的总天数
    var week1,week2,week3,week4,week5;
    week1 = getFirstWeek();   //第一周天数     week2、week3、week4、week5第几周天数
    if(weeks==4){
        week2 = week3 = 7;
        week4 = days - week1 - week2 -week3;
        document.write('第一周:'+week1+' ,第二周:'+week2+' ,第三周:'+week3+' ,第四周:'+week4);
    }else{
        week2 = week3 = week4 = 7;
        week5 = days - week1 - week2 -week3 - week4;
        //alert(week5);
        document.write('第一周:'+week1+' ,第二周:'+week2+' ,第三周:'+week3+' ,第四周:'+week4+' ,第五周:'+week5);
    }

  }


  getWeekOfDay();





  </script>

 

posted on 2015-01-20 10:53  雨为我停  阅读(575)  评论(0编辑  收藏  举报