【发布时间】:2021-06-28 21:36:50
【问题描述】:
我这里有一个 UTC 字符串。
2021-04-01T21:26:19Z
我想使用 date-fns 中的 PPP 格式将其转换为人类可读的格式
April 1st, 2021
我该怎么做呢?我似乎在 date-fns 中找不到将 UTC 字符串转换为不同日期的函数
我的代码如下所示:
import { isValid, format, parse } from 'date-fns'
import { enGB } from 'date-fns/locale'
export const getReadableDate = (utcDate:string | undefined):string => {
if (!utcDate) {
return 'Invalid Date'
}
const parsedDate = parse(utcDate, 'PPP', new Date(), { locale: enGB })
const isValidDate = isValid(parsedDate)
if (isValidDate) {
const messageDate = format(new Date(utcDate), 'PPP')
return messageDate
} else {
return 'InvalidDate'
}
}
【问题讨论】:
标签: javascript date date-fns