日期格式
JavaScript 为我们提供了多种日期格式,从基本的特定于区域设置的格式一直到复杂的自定义选项。了解不同的日期格式是 Web 开发的一个基本和必不可少的方面,无论您是构建动态 Web 应用程序、管理时间敏感数据还是简单地以用户友好的方式显示日期。
在这里,我们将介绍 JavaScript 的不同日期格式,并通过一些示例实现它们以更好地理解它们。下表解释了 JavaScript 中使用的所有不同日期格式。
格式 | 示例 | 描述 |
---|---|---|
ISO Format (UTC) | 2024-01-29T12:34:56.789Z | 具有年、月、日和时间组件的标准化格式。“Z”表示时间采用 UTC(协调世界时)。 |
Locale Date and Time | 1/29/2024, 12:34:56 PM | 这是基于用户系统或浏览器设置的本地化日期和时间表示,并且可能会根据区域设置在符号方面有所不同。 |
Custom Date Format | Jan 29, 2024, 12:34:56 PM PST | 自定义格式允许开发人员指定要包含日期的哪些组成部分(年、月、日、小时、分钟、秒)以及它们应以何种格式出现。 |
Short Date Format | 01/29/24 | 日期的简短表示形式,包括月、日和年。顺序可能因区域设置而异。 |
Long Date Format | January 29, 2024 | 日期的长表示形式,包含完整的月份名称、日期和年份。 |
Short Time Format | 12:34 PM | 用小时和分钟表示时间的简短表示。 |
Long Time Format | 12:34:56 PM | 用小时、分钟和秒表示的时间。 |
UTC Date Format | Tue, 29 Jan 2024 12:34:56 GMT | 协调世界时 (UTC) 格式的日期和时间字符串。它包括星期几和时区缩写 (GMT)。 |
Epoch Timestamp | 1643450096789 | 自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。也称为 Unix 时间戳。用于以数字形式处理和比较日期。 |
Relative Time | 2 hours ago, 3 days ago | 一种人类可读的格式,以相对方式表示时差,例如“ago”表示过去的日期。用于显示自特定日期以来经过的时间。 |
例子
示例 1:以不同格式显示当前日期
此示例中的 JavaScript 在页面上动态生成并显示各种日期格式:ISO 格式、区域设置日期和时间、自定义日期格式;短日期和长日期格式;短时和长时格式;UTC 日期格式,甚至是纪元时间戳。此外,它还计算两个给定日期之间的相对时间 - 将当前日期与指定的前一个日期进行比较,并以人类可读的形式呈现这些结果。此代码示例了使用 JavaScript 在 HTML 上下文中格式化日期的实用技术。
<!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 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 对象来创建 (weekday, month, day, year) 的格式。使用此选项,自定义日期格式,我们不仅可以选择要显示的日期部分,还可以选择它们的顺序。如果网站在某些国家/地区以 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 appendFormattedDate(type, formatFunction) {
const formattedDate = formatFunction(currentDate);
document.body.innerHTML += `<p>${type}: ${formattedDate}</p>`;
}
// 附加自定义日期格式
appendFormattedDate('Custom Date Format', customDateFormat);
</script>
</body>
</html>
示例 3:生成未来 5 天的日期
在此示例中,JavaScript 会根据当前日期生成未来日期,特别是未来五天的日期。随后,它以三种不同的方式格式化和显示这些日期;ISO 格式;特定于区域设置的排列方式和自定义布局将在网页上展示。无需任何用户输入,JavaScript 的日期处理功能就可以通过从 generateFutureDates 函数动态生成的日期接收实际说明。
<!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); //每次迭代增加1天
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>