新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

JS 获取当前月份的所有日期集合,js获取当前月份的天数

发布时间:2023-12-19 03:43:52

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

要获得当前月份的所有日期集合,可使用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打印出来查看结果。