可能重复:
How to determine number Saturdays and Sundays comes between two dates in java script
我希望使用javascript
找到一个月内的星期日我将月份和年份传递给函数
我可以使用
计算总天数 <script type="text/javascript">
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
</script>
但需要找不到星期日
请建议
答案 0 :(得分:5)
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
function sundays(year, month) {
var day, counter, date;
day = 1;
counter = 0;
date = new Date(year, month, day);
while (date.getMonth() === month) {
if (date.getDay() === 0) { // Sun=0, Mon=1, Tue=2, etc.
counter += 1;
}
day += 1;
date = new Date(year, month, day);
}
return counter;
}
console.log(sundays(2012, 5));
答案 1 :(得分:1)
function sundaysInMonth( m, y ) {
var days = new Date( y,m,0 ).getDate();
var sundays = [ (8 - (new Date( m +'/01/'+ y ).getDay())) % 7 ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays;
}
alert( sundaysInMonth( 10,2012 ) ); //=> [ 7,14,21,28 ]
alert( sundaysInMonth( 10,2012 ).length ); //=> 4