JavaScript 格式化日期和时间的方法

871 阅读3分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第16天,点击查看活动详情

使用 Date.toLocaleString() 方法格式化日期和时间

Date.toLocaleString() 方法可用于从 Date 对象创建格式化的日期和时间字符串。

它接受两个参数:格式化字符串的 locale 和格式化 options 对象。

locale 通常是一种语言代码。例如,对于中文,使用的是 zh-cnoptions 对象包括 dateStyletimeStyle 等设置(两者都接受 fulllongmiddleshort 的值)。

let now = new Date()

// 获取格式化字符串
let formatDate = now.toLocaleString('en-US', {
  dateStyle: 'long',
  timeStyle: 'short',
  hour12: true
}) // '2022年3月29日 下午4:36'

格式因位置而异

locale 参数控制格式约定。

例如,使用英式英语(en-UK)或美式英语(en-US),我们的日期和时间返回格式略有不同。

new Date().toLocaleString('en-UK', {
  dateStyle: 'long',
  timeStyle: 'short',
  hour12: true
}) // '29 March 2022, 04:40 pm'

new Date().toLocaleString('en-US', {
  dateStyle: 'long',
  timeStyle: 'short',
  hour12: true
}) // 'March 29, 2022 at 4:40 PM'

我们可以使用 navigator.language 属性将日期字符串自动格式化为用户的 locale

// 这将自动使用用户的浏览器语言进行格式化
new Date().toLocaleString(navigator.language, {
  dateStyle: 'long',
  timeStyle: 'short',
  hour12: true
}) // '2022年3月29日 下午4:41'

使用 Intl.DateTimeFormat() 构造函数转换和格式化日期和时间

Intl 对象的设计目的是使特定位置的数据更容易国际化。DateTimeFormat() 是一种用于格式化日期和时间的方法。

首先,创建一个新的 Intl.DateTimeFormat() 实例。

它接受一个 locale(例如,zh-CN 代表中文,en-US 代表美式英语,en-GB 代表英式英语)。此参数告诉方法将日期和时间格式化为哪种语言。

const formatter = new Intl.DateTimeFormat('zh-CN')
const formatter = new Intl.DateTimeFormat('en-US')
const formatter = new Intl.DateTimeFormat('en-GB')

使用一系列 options 作为第二个参数,可以对输出的格式进行更细粒度的控制。

例如:以下示例使用 dateStyle 属性,然后使用 format 格式化为字符串:

const now = new Date()

new Intl.DateTimeFormat('zh-CN', { dateStyle: 'full' }).format(now) // '2022年3月30日星期三'
new Intl.DateTimeFormat('zh-CN', { dateStyle: 'long' }).format(now) // '2022年3月30日'
new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium' }).format(now) // '2022年3月30日'
new Intl.DateTimeFormat('zh-CN', { dateStyle: 'short' }).format(now) // '2022/3/30'
new Intl.DateTimeFormat('en-US', { dateStyle: 'long' }).format(now) // 'March 30, 2022'

new Intl.DateTimeFormat('en-CA', { dateStyle: 'short' }).format(now) // '2022-03-30'

您可以查看 options 参数的完整列表,以及它们在 Mozilla 开发者网络上的功能。

Intl.DateTimeFormat()Date.toLocaleString() 有什么区别

Date.toLocalString() 方法的旧实现不支持 localeoptions 参数,并且只使用当前用户的语言环境。

Intl.DateTimeFormat() 方法推出后,可选的 options 也被纳入 Date.toLocaleString()

如果您使用相同的选项格式化多个日期,Intl.DateTimeFormat() 方法将为您提供更好的性能,应该是首选方法。否则,它们在行为上是相同的。

浏览器兼容性

Intl.DateTimeFormat() 方法适用于所有现代浏览器,也适用于 IE 11。

Intl.DateTimeFormat