js已经获取到当前的系统时间是2016.8.5,如何获取八月中有多少个周?
补充:
严格意义上讲是获取跨的周数,比如说8.1是周日,也单独算一周
补充:
最后自己写了一个函数获取周数,我获取的是2016年里面某个月份的周数,如果要获取不同的年份,请传递参数进去
function getWeeks(m){
var str=new Date('2016-'+m+'-1');
// 当前年份
var year=str.getFullYear();
// 获取月份第一天是周几 周日是0
var day=str.getDay();
// 获取当前月份的天数
var days=new Date(year,m,0).getDate();
// 要减去开头的这几天
var first=0;
day==0? first=1 : first=8-day;
days = days-first;
return 1+ Math.ceil(days/7);
}
不优雅,但是可用
<script>
alert(getWeeksInMonth( new Date() ))
function getWeeksInMonth( date ) {
var end = new Date( date.getFullYear(), date.getMonth() + 2, 0 );
var start = new Date( date.getFullYear(), date.getMonth() + 1 , 1 );
return getWeeksInYear( end ) - getWeeksInYear( start ) + 1;
}
// http://zerosixthree.se/snippets/get-week-of-the-year-with-jquery/
function getWeeksInYear( date ) {
var onejan = new Date( date.getFullYear(), 0, 1 );
return Math.ceil( ( ( ( date - onejan ) / 86400000 ) + onejan.getDay() + 1 ) / 7 );
}
</script>
//定义
function getMonthWeek(a, b, c) {
var date = new Date(a, b, c), w = date.getDay(), d = date.getDate();
return Math.ceil(
(d + 6 - w) / 7
);
}
//调用
var day=new Date();
lastCurDay = new Date(day.getFullYear(), day.getMonth() + 1, 0);//获取当前月最后一天时间
getMonthWeek(lastCurDay.getFullYear(), lastCurDay.getMonth(), lastCurDay.getDate())
Date.prototype.getWeekCountInCurrentMonth = function(){
var date = new Date();
date.setDate(1);
var day = date.getDay() || 7;
date.setMonth(date.getMonth() + 1);
var endDay = date.getDay() || 7;
if (day == endDay && day == 1){
return 4;
}else{
return 5 + (day >= endDay && endDay != 1);
}
}
可以为Date.prototype添加一个获取周数的方法
Date.prototype.getWeeks = function(){
//do something
}