JavaScript >> Javascript 文檔 >  >> Tags >> string

如何在 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));
// الاثنين، ١٣ سبتمبر ٢٠٢١ ٠٠٠ غرينتش-٥

Tutorial JavaScript 教程
  1. 用 JS 製作自己的動畫

  2. Hackitect 系列 vol.3 - Building 為開發者奪旗

  3. 白板:React Hooks

  4. Javascript 確認對話框

  5. 為什麼你應該避免在 Node.js 中長時間運行遞歸。

  6. JavaScript 中的計算機科學:鍊錶

  7. 我們如何從 php 中的腳本傳遞一個變量並將其設置為新的變量?(關閉)

  1. 在 React 中傳遞道具

  2. 前端環境變量——什麼、為什麼和如何

  3. 如何使用 jquery 獲取突出顯示的文本位置

  4. 為 JavaScript 項目創建 GitHub 構建

  5. 每次將 i 與 array.length 進行比較時,循環是否都會檢查 array.length?

  6. 找出我構建的 8 個新的 chakraUI 組件

  7. 具有特殊字符的Javascript正則表達式密碼驗證

  1. 將 React 組件發佈到節點包管理器 (NPM) 的工具包

  2. Webhook 上的簡單操作方法:恐嚇現在停止

  3. 在 React Native 中通過上下文輸入配置

  4. 使用 TypeScript、Prisma 和 Next.js 構建 Twitter 克隆