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 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 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 会根据当前日期生成未来 5 天的日期。随后,它会以三种不同的方式格式化和显示这些日期: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); // 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>

