溫馨提示×

JS 獲取當前月份的所有日期集合

js
小億
381
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函數會返回一個包含當前月份的所有日期的數組??梢允褂?code>console.log打印出來查看結果。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女