Search code examples
javascriptdatedate-fns

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


I have a UTC string here.

2021-04-01T21:26:19Z

I'd like to convert it to a human readable format using PPP format from date-fns

April 1st, 2021

how do I go about doing this? I can't seem to find a function in date-fns that convert a UTC string to a different date

My code looks like this:

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

Solution

  • You can use parseISO, which accepts a UTC timestamp and returns a 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'
      }
    }
    

    You can also use parse, but the second argument should be the format you want to parse from, instead of the format you want to display as. In your example, you should use "yyyy-MM-dd'T'HH:mm:ss'Z'" (the ISO format) when you call parse, and "PPP" when you call format.