作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我写了一个函数来给我一个月的所有日子,不包括周末。一切正常,但是当我想获得 12 月的天数时,Date 对象返回下周的 1 月 1 日,并且该函数返回一个空数组。
请提供任何帮助。
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
这也适用于您获取月份时 - 它还返回 0 到 11
我很惊讶你说
Every thing works fine
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))
关于javascript - 如何获取一个月中不包括周末的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296064/
我是一名优秀的程序员,十分优秀!