首页 > 解决方案 > UTC 日期时间到 ES6 中的完整日期

问题描述

我怎样才能将其转换2021-01-10 12:47:29 UTCJanuary 10, 2021?

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

标签: javascriptreactjsecmascript-6momentjsmoment-timezone

解决方案


Moment.js 已弃用。这是使用本机 JS 功能的替代方案。

首先,我们需要将日期字符串转换为Date对象。如 MDN 上的构造函数页面所述,调用new Date(video?.createdAt)不可靠:Date()

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

有关正确格式的参考,请参阅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()可能无法满足您的需求。在这些情况下,使用推荐的 Moment.js 替代方案之一可能会很有用。


推荐阅读