如何在 JavaScript 中獲取當前日期、月份和年份
Date
對象方法 getDate()
, getMonth()
, 和 getFullYear()
可用於從 JavaScript 中的日期對像中檢索日、月和全年。
這是一個例子:
const date = new Date(2021, 8, 18);
const day = date.getDate();
const month = date.getMonth() + 1; // getMonth() returns month from 0 to 11
const year = date.getFullYear();
const str = `${day}/${month}/${year}`;
console.log(str);
// 18/9/2021
注意 getDate()
, getMonth()
, 和 getFullYear()
方法返回運行代碼的計算機的本地時區的日期和時間。
要獲取通用時區 (UTC) 中的日期和時間,只需將上述方法替換為 getUTCDate()
, getUTCMonth()
, 和 getUTCFullYear()
分別:
const date = new Date(2021, 8, 18);
const day = date.getUTCDate();
const month = date.getUTCMonth() + 1; // getUTCMonth() returns month from 0 to 11
const year = date.getUTCFullYear();
const str = `${day}/${month}/${year}`;
console.log(str);
// 18/9/2021