温馨提示×

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

js
小亿
100
2023-12-19 03:43:52
栏目: 编程语言

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

0