ES6 中的 UTC 日期时间到完整日期

问题描述

我如何将这个 2021-01-10 12:47:29 UTC 转换为 January 10,2021?

我在下面使用 moment.js 使用它,但这适用于浏览器,但不适用于 Safari {moment(video?.createdAt).format('MMMM D,YYYY')}

解决方法

Moment.js is deprecated. 这是使用原生 JS 功能的替代方法。

首先我们需要将日期字符串转换为 Date 对象。如 Date() constructor page on MDN 所述,调用 new Date(video?.createdAt) 不可靠:

使用 Date 构造函数解析日期字符串 (和 Date.parse(),其工作方式相同) 由于浏览器的差异和不一致,强烈建议

有关正确格式的参考,请参阅 Date Time String Format on MDN。例如:

// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
  const [date,time] = dateString.split(' ')
  return new Date(`${date}T${time}.000Z`) // Z = UTC
}

然后我们可以使用 Date.prototype.toLocaleString() 来格式化 Date 对象:

// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
  const [date,time] = dateString.split(' ')
  return new Date(`${date}T${time}.000Z`) // Z = UTC
}

function format(dateString) {
  if (!dateString) return 'some fallback value'

  const date = parseDate(dateString)
  return date.toLocaleString('en',{
    year: 'numeric',month: 'long',day: 'numeric',hour: 'numeric',minute: 'numeric',})
}

console.log(format('2021-01-10 12:47:29 UTC'))
//=> January 10,2021,2:47 PM

console.log(format(undefined))
//=> some fallback value

有关所有可能的选项,请参阅 Intl.DateTimeFormat()。例如,这些选项产生的结果略有不同:

return date.toLocaleString('en',{
  dateStyle: 'long',timeStyle: 'short',})

format('2021-01-10 12:47:29 UTC')
//=> January 10,2021 at 2:47 PM

如果日期字符串可以是各种格式,您可能需要更强大的日期解析。或者,如果您需要异国情调的格式,toLocaleString() 可能无法满足您的需求。在这些情况下,使用 recommended Moment.js alternatives 之一可能会很有用。

,

新的 Intl DateTimeFormat API 在许多浏览器中获得了更多的原生支持,因此它是一个更具前瞻性的解决方案。按照文档中的建议,您可以将 polyfills 用于不完全支持此功能的浏览器。不幸的是,Safari 是尚未赶上的浏览器之一。

实现您正在寻找的内容的简短片段

new Intl.DateTimeFormat('en-US',{ dateStyle: 'long'}).format(new Date("2021-01-10 12:47:29Z"))  // outputs January 10,2021

请记住,末尾没有 Z 的日期时间字符串将被解析为本地时间。 Z 表示提供的日期时间为 UTC。

,

如果您正在寻找 moment.js 替代品,我建议您使用 date-fns。这是一个比较两个的 blog post

这是 date-fns 的 format 文档。

所以要使用 date-fns 回答您的问题:

format(new Date(video?.createdAt),'MMMM D,YYYY')

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...