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>
广告

© . All rights reserved.