JavaScript - 日期格式



日期格式

JavaScript 為我們提供了各種日期格式,從基本的區域設定特定格式到複雜的自定義選項。瞭解不同的日期格式是 Web 開發的一個基本且必不可少的方面,無論您是構建動態 Web 應用程式、管理時間敏感資料,還是僅僅以使用者友好的方式顯示日期。

在這裡,我們將介紹 JavaScript 的不同日期格式,並透過一些示例來實現它們,以便更好地理解它們。下表解釋了 JavaScript 中使用的所有不同日期格式。

格式 示例 描述
ISO 格式 (UTC) 2024-01-29T12:34:56.789Z 標準化格式,包含年份、月份、日期和時間元件。'Z' 表示時間為 UTC(協調世界時)。
區域設定日期和時間 1/29/2024, 12:34:56 PM 它是基於使用者系統或瀏覽器設定的本地化日期和時間表示形式,根據區域設定的不同,符號可能會有所不同。
自定義日期格式 Jan 29, 2024, 12:34:56 PM PST 自定義格式允許開發人員指定要包含的日期元件(年份、月份、日期、小時、分鐘、秒)以及它們的格式。
短日期格式 01/29/24 月份、日期和年份的簡短日期表示形式。順序可能因區域設定而異。
長日期格式 January 29, 2024 包含完整月份名稱、日期和年份的長日期表示形式。
短時間格式 12:34 PM 小時和分鐘的簡短時間表示形式。
長時間格式 12:34:56 PM 包含小時、分鐘和秒的長時間表示形式。
UTC 日期格式 Tue, 29 Jan 2024 12:34:56 GMT 協調世界時 (UTC) 格式化的日期和時間字串。它包括星期幾和時區縮寫 (GMT)。
紀元時間戳 1643450096789 自 1970 年 1 月 1 日 00:00:00 UTC 以來以毫秒為單位的時間。也稱為 Unix 時間戳。用於將日期作為數字處理和比較。
相對時間 2 hours ago, 3 days ago 以相對方式表示時間差的人類可讀格式,例如過去日期的“ago”。用於顯示自某個日期以來經過了多少時間。

示例

示例 1:以不同的格式顯示當前日期

本示例中的 JavaScript 程式碼動態生成並在頁面上顯示各種日期格式:ISO 格式、本地日期和時間、自定義日期格式;短日期和長日期格式;短時間和長時間格式;UTC 日期格式,甚至紀元時間戳。此外,它還計算兩個給定日期之間的相對時間——將當前日期與指定的先前日期進行比較,並將結果以人類可讀的形式呈現。此程式碼舉例說明了在 HTML 上下文中使用 JavaScript 格式化日期的實用技術。

<!DOCTYPE html>
<html>
<body>
   <h2>All Types of Date Formats</h2>
   <script>
      const currentDate = new Date();

      function appendFormattedDate(type, formatFunction) {
         const formattedDate = formatFunction(currentDate);
         const paragraph = document.createElement('p');
         paragraph.innerText = `${type}: ${formattedDate}`;
         document.body.appendChild(paragraph);
      }

      appendFormattedDate('ISO Format (UTC)', date => date.toISOString());

      appendFormattedDate('Locale Date and Time', date => date.toLocaleString());

      const options = { 
         year: 'numeric', 
         month: 'short', 
         day: 'numeric', 
         hour: '2-digit', 
         minute: '2-digit', 
         second: '2-digit', 
         timeZoneName: 'short' 
      };
      appendFormattedDate('Custom Date Format', date => date.toLocaleString('en-US', options));

      appendFormattedDate('Short Date Format', date => date.toLocaleDateString());
      appendFormattedDate('Long Date Format', date => date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }));

      appendFormattedDate('Short Time Format', date => date.toLocaleTimeString());
      appendFormattedDate('Long Time Format', date => date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' }));

      appendFormattedDate('UTC Date Format', date => date.toUTCString());
      appendFormattedDate('Epoch Timestamp', date => date.getTime());

      const previousDate = new Date('2024-01-29T00:00:00Z');
        
      const relativeTime = formatRelativeTime(previousDate, currentDate);
      appendFormattedDate('Relative Time', () => relativeTime);

      // Function to calculate relative time
      function formatRelativeTime(previousDate, currentDate) {
         const elapsedMilliseconds = currentDate - previousDate;
         const seconds = Math.floor(elapsedMilliseconds / 1000);
         const minutes = Math.floor(seconds / 60);
         const hours = Math.floor(minutes / 60);

         if (seconds < 60) {
            return `${seconds} second${seconds !== 1 ? 's' : ''} ago`;
         } else if (minutes < 60) {
            return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
         } else if (hours < 24) {
            return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
         } else {
            return 'More than a day ago';
         }
      }
   </script>
</body>
</html>

示例 2:自定義日期格式

此示例使我們更深入地瞭解自定義日期格式,這些格式沒有任何字首格式,並且由開發人員自行選擇。我們使用 Intl.DateTimeFormat 物件建立我們自己的格式(星期幾、月份、日期、年份)。使用此自定義日期格式選項,我們不僅可以選擇要顯示的日期部分,還可以選擇它們的順序。對於某些國家/地區,如果網站以 dd/mm/yyyy 格式顯示日期可能更合適,而在其他國家/地區,以 mm-dd-yyyy 格式顯示日期可能更友好。

<!DOCTYPE html>
<html>
<body>
   <h2>Custom Date Format Example</h2>
   <script>
      const currentDate = new Date();
     
      function customDateFormat(date) {
         const options = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' };
         return new Intl.DateTimeFormat('en-US', options).format(date);
      }

      // Function to append formatted date to the body
      function appendFormattedDate(type, formatFunction) {
         const formattedDate = formatFunction(currentDate);
         document.body.innerHTML += `<p>${type}: ${formattedDate}</p>`;
      }

      // Append custom date format
      appendFormattedDate('Custom Date Format', customDateFormat);
   </script>
</body>
</html>

示例 3:生成未來 5 天的日期

在此示例中,JavaScript 生成未來日期,具體來說是基於當前日期的未來五天。隨後,它以三種不同的方式格式化並顯示這些日期;在網頁上展示了 ISO 格式、特定於區域設定的排列和自定義佈局。無需任何使用者輸入,透過 generateFutureDates 函式動態生成的日期,JavaScript 的日期處理功能得到了實際的說明。

<!DOCTYPE html>
<html>
<body>
   <h2>Future Dates Generator</h2>
   <div id="futureDates"></div>
   <script>
      function generateFutureDates() {
         const today = new Date();
         const futureDatesDiv = document.getElementById('futureDates');

         for (let i = 1; i <= 5; i++) {
            const futureDate = new Date(today.getTime() + i * 24 * 60 * 60 * 1000); // Adding 1 day for each iteration
            const isoFormat = futureDate.toISOString();
            const localeFormat = futureDate.toLocaleString();
            const customFormatOptions = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'short' };
            const customFormat = futureDate.toLocaleString('en-US', customFormatOptions);

            futureDatesDiv.innerHTML += `
            <p><strong>Day ${i}:</strong></p>
            <p>ISO Format (UTC): ${isoFormat}</p>
            <p>Locale Date and Time: ${localeFormat}</p>
            <p>Custom Format: ${customFormat}</p>
            <hr>
            `;
         }
      }

      generateFutureDates();
   </script>
</body>
</html>
廣告