[JS] 日期

取得格式為 YYYY-MM-DD 的今天日期。

下面是問 ChatGPT 的結果:

const today = new Date();

const year = today.getFullYear();

// 月份從 0 開始,所以要加 1,並確保兩位數
const month = String(today.getMonth() + 1).padStart(2, '0');

// 確保日期為兩位數
const day = String(today.getDate()).padStart(2, '0');

const formattedDate = `${year}-${month}-${day}`;

// 2024-05-23
console.log(formattedDate);

在網路上還看到其他方式:

const today = new Date();

const year = today.getFullYear();
const month = ('0' + (today.getMonth() + 1)).slice(-2);
const date = ('0' + today.getDate()).slice(-2);

const hours = ('0' + today.getHours()).slice(-2);
const minutes = ('0' + today.getMinutes()).slice(-2);
const seconds = ('0' + today.getSeconds()).slice(-2);

// 2024-05-23 10:55:11
console.log(`${year}-${month}-${date} ${hours}:${minutes}:${seconds}`);

———

取得最近七天日期。

下面是問 ChatGPT 的結果:

const today = new Date();

for (let i = 0; i < 7; i++) {
  const tempDate = new Date();

  // 設定日期為今天減去 i 天
  tempDate.setDate(today.getDate() - i);

  const year = tempDate.getFullYear();

  // 月份從 0 開始,所以要加 1,並確保兩位數
  const month = String(tempDate.getMonth() + 1).padStart(2, '0');

  // 確保日期為兩位數
  const day = String(tempDate.getDate()).padStart(2, '0');

  const formattedDate = `${year}-${month}-${day}`;
  
  console.log(formattedDate);
}

在網路上看到的方式:

const today = new Date();

for (let i = 0; i < 7; i++) {
  const newDate = new Date(today.getTime() - i * 24 * 60 * 60 * 1000);
  
  const year = newDate.getFullYear();
  const month = String(newDate.getMonth() + 1).padStart(2, '0');
  const day = String(newDate.getDate()).padStart(2, '0');
  
  const formattedDate = `${year}-${month}-${day}`;
  
  console.log(formattedDate);
}


其他參考連結:

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

返回頂端