繁体   English   中英

在 date-fns 库中将 UTC 时间戳字符串转换为人类可读的格式

[英]Convert UTC time stamp string to human-readable format in date-fns library

我这里有一个 UTC 字符串。

2021-04-01T21:26:19Z

我想使用 date-fns 中的PPP格式将其转换为人类可读的格式

April 1st, 2021

我该怎么做? go 我似乎无法在 date-fns 中找到将 UTC 字符串转换为不同日期的 function

我的代码如下所示:

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'
  }
}

您可以使用parseISO ,它接受 UTC 时间戳并返回Date object:

import { isValid, format, parseISO } from 'date-fns'

export const getReadableDate = (utcDate: string | undefined): string => {
  if (!utcDate) {
    return 'Invalid Date'
  }

  const parsedDate = parseISO(utcDate)
  const isValidDate = isValid(parsedDate)
  if (isValidDate) {
    // parsedDate is a `Date` object, so you can use it directly,
    // instead of `new Date(utcDate)`
    const messageDate = format(parsedDate, 'PPP')
    return messageDate
  } else {
    return 'InvalidDate'
  }
}

您也可以使用parse ,但第二个参数应该是您要从中解析的格式,而不是您要显示的格式。 在您的示例中,调用parse时应使用"yyyy-MM-dd'T'HH:mm:ss'Z'" (ISO 格式),调用format时应使用"PPP"

这适用于 Typescript

export const getReadableDate = (utcDate:string | undefined):string => {
  if (!utcDate) {
    return 'Invalid Date'
  }

  const options = { year: 'numeric', month: 'long', day: 'numeric' }
  // @ts-ignore
  return new Date(utcDate).toLocaleDateString(undefined, options)
}

但我想看看像date-fns这样的其他库是如何实现这种转换的,我觉得这是一项非常常见的任务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM