簡體   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