Javascript 简明教程

JavaScript - Date Formats

Date Formats

JavaScript 为我们提供了从基本的特定于语言环境的格式化到复杂自定义选项的各种 date formats 。了解不同的日期格式是 Web 开发的基础和必不可少的一个方面,无论您是构建动态 Web 应用程序、管理时间敏感数据还是仅仅以用户友好的方式显示日期。

JavaScript offers us a variety of date formats ranging from elementary locale-specific formatting all the way up to sophisticated customization options. Understanding the different date formats is a fundamental and essential aspect of web development, irrespective of whether you’re building a dynamic web application, managing time sensitive data or simply displaying dates in a user-friendly manner.

在这里,我们将介绍 JavaScript 的不同日期格式,并通过一些示例来实现它们以更好地理解它们。以下是一个表,解释了 JavaScript 中使用的所有不同日期格式。

Here, we are going to cover different date formats of JavaScript and implement them with a few examples to understand them better. Below is a table explaining all the different date formats used in JavaScript.

Format

Example

Description

ISO Format (UTC)

2024-01-29T12:34:56.789Z

Standardized format with the year, month, day, and time components. The 'Z' indicates the time is in UTC (Coordinated Universal Time).

Locale Date and Time

1/29/2024, 12:34:56 PM

It is the localized date & time representation based on the user’s system or browsers settings and can vary in terms of symbols depending on the locale.

Custom Date Format

Jan 29, 2024, 12:34:56 PM PST

The custom format allows developers to specify which components of the date (year, month, day, hour, minute, second) are to be included and in what format they should be occurring.

Short Date Format

01/29/24

A short representation of the date with the month, day, and year. The order may vary based on the locale.

Long Date Format

January 29, 2024

A long representation of the date with the full month name, day, and year.

Short Time Format

12:34 PM

A short representation of the time with hours and minutes.

Long Time Format

12:34:56 PM

A long representation of the time with hours, minutes, and seconds.

UTC Date Format

Tue, 29 Jan 2024 12:34:56 GMT

Coordinated Universal Time (UTC) formatted date and time string. It includes the day of the week and the timezone abbreviation (GMT).

Epoch Timestamp

1643450096789

The number of milliseconds since January 1, 1970, 00:00:00 UTC. Also known as Unix Timestamp. Useful for handling and comparing dates as numbers.

Relative Time

2 hours ago, 3 days ago

A human-readable format that expresses the time difference in a relative manner, such as "ago" for past dates. Useful for displaying how much time has passed since a certain date.

Examples

Example 1: Displaying current date in different formats

此示例中的 JavaScript 会动态生成和显示页面上的各种日期格式:ISO 格式、区域日期和时间、自定义日期格式;日期的短格式和长格式;时间的短格式和长格式;UTC 日期格式,甚至还有纪元时间戳。此外,它还会计算两个给定日期之间的相对时间——当前日期与指定的过去日期进行比较,并将这些结果以人类可读的形式展示出来。此代码举例说明了在 HTML 上下文中使用 JavaScript 格式化日期的实用技术。

JavaScript in this example dynamically generates and displays a variety of date formats on the page: ISO format, locale date and time, custom date format; short and long date formats; short and long time formats; UTC date format, even an epoch timestamp. Furthermore, it calculates the relative time between two given dates – current one being compared to a specified previous one and presents these results in human-readable form. This code exemplifies pragmatic techniques for formatting dates within an HTML context using 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>

Example 2: Customized date formats

此示例让我们更深入地了解没有前缀格式并且由开发人员选择使用的自定义日期格式。我们使用 Intl.DateTimeFormat 对象创建我们的格式(星期、月份、日期、年份)。使用此选项自定义日期格式,我们不仅可以选择要显示的日期部分,还可以选择它们的顺序。如果一个网站在某些国家/地区以 dd/mm/yyyy 显示日期,而如果在某些其他国家/地区以 mm-dd-yyyy 显示日期,则可能更合适。

This example gives us a deeper understanding of the customized date formats which do not have any prefix format and are up to the developer choose. We use the Intl.DateTimeFormat object to create our format of (weekday, month, day, year). With this option customized date formats we can choose not only the parts of the date to be made visible but also their order. A website might be more suitable if it displayed dates in dd/mm/yyyy in some countries but more user friendly if it displayed dates in mm-dd-yyyy in some other countries.

<!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>

Example 3: Generating next 5 days dates

在此示例中,JavaScript 生成了未来的日期,特别是基于当前日期的未来五天的日期。然后,它以三种不同的方式对这些日期进行格式化并显示:在网页上展示了 ISO 格式;区域特定的排列和自定义布局。无需任何用户输入,JavaScript 的日期处理功能即可通过 generateFutureDates 函数动态生成的日期获得实际的说明。

In this example JavaScript generates future dates, specifically for the next five days based on the current date. Subsequently, it formats and displays these dates in three different ways; ISO format; locale-specific arrangement, and a custom layout are showcased on the web page. Without requiring any user input, JavaScript’s date handling capabilities receive a practical illustration through dynamically generated dates from the generateFutureDates function.

<!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>