如何在 JavaScript 中將日期格式化為字符串
有多種方法可以在 JavaScript 中格式化日期。您可以使用 toUTCString()
等內置方法 和 toISOString()
, 或 Intl.DateTimeFormat
對象。
內置方法
Date
JavaScript 中的 object 公開了幾個內置方法,您可以使用這些方法以不同的格式顯示日期。
默認情況下,toString()
方法以全文字符串格式輸出日期:
const date = new Date(2021, 8, 14, 7, 14);
console.log(date.toString());
// OR
console.log(date);
// Tue Sep 14 2021 07:14:00 GMT+0500 (Pakistan Standard Time)
要將日期顯示為 UTC 字符串,您可以使用 toUTCString()
方法:
console.log(date.toUTCString());
// Tue, 14 Sep 2021 02:14:00 GMT
如果要以 ISO 格式顯示日期,請使用 toISOString()
替代方法:
console.log(date.toISOString());
// 2021-09-14T02:14:00.000Z
同樣,您可以使用 toDateString()
和 toTimeString()
僅顯示 Date
的日期和時間部分的方法 對象,分別:
console.log(date.toDateString());
// Tue Sep 14 2021
console.log(date.toTimeString());
// 07:14:00 GMT+0500 (Pakistan Standard Time)
您不僅限於上述方法。當然,你也可以使用像 getDate()
這樣的方法 , getMonth()
, 和 getFullYear()
從 JavaScript 中的日期對像中檢索日、月和全年:
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const str = `${day}/${month}/${year}`;
console.log(str);
// 14/9/2021
Intl.DateTimeFormat
方法
Intl.DateTimeFormat
對像在所有現代瀏覽器和 IE 11 中都可用。它提供了 JavaScript 中對語言敏感的日期和時間格式化的方法。
一種這樣的方法是 format()
根據 Intl.DateTimeFormat
的語言環境和格式化選項格式化日期 對象。
下面是一個使用默認語言環境格式化日期的示例:
const date = new Date(2021, 8, 14, 7, 14);
const str = Intl.DateTimeFormat().format(date);
console.log(str);
// 14/9/2021
如果您需要更本地化的日期和時間格式,只需將所需的語言環境傳遞給 Intl.DateTimeFormat()
如下圖:
console.log(new Intl.DateTimeFormat('de-DE').format(date));
// 14.9.2021
console.log(new Intl.DateTimeFormat('ko-KR').format(date));
// 2021. 9. 14.
console.log(new Intl.DateTimeFormat('ar-EG').format(date));
// ١٤/٩/٢٠٢١
可以通過傳遞 options
進一步自定義日期對象 反對Intl.DateTimeFormat()
構造函數:
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
console.log(new Intl.DateTimeFormat('de-DE', options).format(date));
// Dienstag, 14. September 2021
options.timeZone = 'CET';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('it-IT', options).format(date));
// martedì 14 settembre 2021, GMT+2
options.fractionalSecondDigits = 3;
console.log(new Intl.DateTimeFormat('ar-EG', options).format(date));
// الاثنين، ١٣ سبتمبر ٢٠٢١ ٠٠٠ غرينتش-٥