javascript - UTC 日期时间到 ES6 中的完整日期
问题描述
我怎样才能将其转换2021-01-10 12:47:29 UTC
为January 10, 2021?
我在下面使用 moment.js 但这适用于浏览器,但不适用于 Safari
{moment(video?.createdAt).format('MMMM D, YYYY')}
解决方案
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 替代方案之一可能会很有用。
推荐阅读
- javascript - 如何将类似对象的数组转换为 JSON 对象,我将能够将其保存到 firebase 数据库中
- windows - 如何制作自定义批处理文件
- javascript - 错误:ReactJS 中的未知规则类型用户名
- css - 当它有 2 个输入时,给一个样式以在 AlertController 上显示完整的按钮
- mysql - 如何将此子查询转换为联接?
- ruby-on-rails - 无法使用 logstash-logger gem 将日志发送到另一台服务器中的 logstash
- javascript - 在不删除折叠行的情况下搜索表
- java - firestore collectionreference .get() 未执行
- matlab - matlab中给定函数的时间序列逼近
- angular - NativeScript 没有得到 Set-Cookie