发布时间:2025-12-11 00:55:30 浏览次数:2
要获取当前月份的所有日期集合,可以使用JavaScript中的Date对象和循环来实现。具体步骤如下:
创建一个Date对象,该对象将自动设置为当前日期。使用getDate方法获取当前月份的第一天的日期。使用getMonth方法获取当前月份的月份。使用getFullYear方法获取当前年份。使用getDaysInMonth函数获取当前月份的天数。使用循环从第一天到最后一天,生成日期集合。下面是一个示例代码:
function getDatesInCurrentMonth() { const currentDate = new Date(); const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); const month = currentDate.getMonth(); const year = currentDate.getFullYear(); const daysInMonth = getDaysInMonth(month, year); const dates = []; for (let i = 0; i < daysInMonth; i++) { const date = new Date(year, month, i + 1); dates.push(date); } return dates;}function getDaysInMonth(month, year) { return new Date(year, month + 1, 0).getDate();}const datesInCurrentMonth = getDatesInCurrentMonth();console.log(datesInCurrentMonth);在上面的示例代码中,getDatesInCurrentMonth函数会返回一个包含当前月份的所有日期的数组。可以使用console.log打印出来查看结果。