如何获得一个月内的天数,不包括周末 [英] How to get number of days in a month excluding weekends
本文介绍了如何获得一个月内的天数,不包括周末的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个功能,给我一个月的所有日子,不包括周末。一切正常,但是当我想要12月的时候,Date对象返回下周的01月1日,该函数返回一个空数组。
I have written a function to give me all days of a month excluding weekends. Every thing works fine but when I want to get December days the Date object returns 01 Jan of next week and the function returns an empty array.
请帮助。
function getDaysInMonth(month, year) {
var date = new Date(year, month-1, 1);
var days = [];
while (date.getMonth() === month) {
// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day
if (weekDay !== 1 && weekDay !== 2) {
days.push(day);
}
date.setDate(date.getDate() + 1);
}
return days;
}
alert(getDaysInMonth(month, year))
推荐答案
当您创建日期时,您使用月份= 0到11
When you create a date, you use month = 0 to 11
当您获得月份时,这也是适用的 - 它也会返回0到11
This also goes for when you GET the month - it also returns 0 to 11
我很惊讶你说
每件事工作正常
Every thing works fine
它实际上从来没有工作过任何月份 - 总是会返回一个空数组
It actually never worked for any month - always would return an empty array
function getDaysInMonth(month, year) {
month--; // lets fix the month once, here and be done with it
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day
if (weekDay%6) { // exclude 0=Sunday and 6=Saturday
days.push(day);
}
date.setDate(date.getDate() + 1);
}
return days;
}
alert(getDaysInMonth(month, year))
这篇关于如何获得一个月内的天数,不包括周末的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文