JS 获取当前月份的所有日期集合

avatar
作者
筋斗云
阅读量:0

要获取当前月份的所有日期集合,可以使用JavaScript中的Date对象和循环来实现。具体步骤如下:

  1. 创建一个Date对象,该对象将自动设置为当前日期。
  2. 使用getDate方法获取当前月份的第一天的日期。
  3. 使用getMonth方法获取当前月份的月份。
  4. 使用getFullYear方法获取当前年份。
  5. 使用getDaysInMonth函数获取当前月份的天数。
  6. 使用循环从第一天到最后一天,生成日期集合。

下面是一个示例代码:

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打印出来查看结果。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!