function WeekMag(year,setWeek) { //year 年, startDay星期几天始 this.year = (new Date).getFullYear(); this.setSw = 7; //默认是7,设置星期四为周开始日 星期天时为7,周1-6->1-6 if (year != null) { this.year = year; //(new Date).getFullYear(); } if (setWeek != null) { this.setSw = setWeek; } //第一周有几天 this.firstWeek = function () { var sDate = new Date(this.year + "-01-01 23:59"); //开始的第一天 var sDay = sDate.getDay(); //开始的第一天是星期几 这个很重要, // var setSw = 4; //设置星期四为周开始日 星期日时为7,周一-六->1-6 if (this.setSw >= sDay) { sDay = this.setSw - sDay; } else if (sDay > this.setSw) { sDay = Math.abs(this.setSw - sDay); //计算第一周有几天 sDay = 7 - sDay; } return sDay; } //获取这一年中的周 this.GetArr = function () { var sDate = new Date(this.year + "-01-01 23:59"); //开始的第一天 var odm = 1000 * 24 * 60 * 60; //一天的毫秒数 var tempArr = []; var Milli = Date.parse(sDate); sDay = this.firstWeek(); for (var i = 0; i < 58; i++) { if (sDay > 0) { if (i == 0) { eDate = new Date(Milli + odm * (sDay - 1)); } else { sDate = new Date(Milli + odm * (sDay + (i - 1) * 7)); //开始的第一天 eDate = new Date(Milli + odm * (sDay + i * 7 - 1)); } } else { sDate = new Date(Milli + odm * (sDay + i * 7)); //开始的第一天 eDate = new Date(Milli + odm * (sDay + (i + 1) * 7 - 1)); } if (eDate.getFullYear() > this.year) { eDate = new Date((this.year + 1).toString() + "-01-01 23:59"); eDate = new Date(Date.parse(eDate) - odm); i = 1000;//无穷大,直接退出 } obj = { "sd": sDate.getFullYear().toString() + "-" + (sDate.getMonth() + 1).toString() + "-" + sDate.getDate().toString(), "ed": eDate.getFullYear().toString() + "-" + (eDate.getMonth() + 1).toString() + "-" + eDate.getDate().toString() }; tempArr.push(obj); } return tempArr; }; } var wm = new WeekMag(2014); wm.GetArr();
计算一年中所有周的时间段