Reputation: 4170
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'
}
}
Upvotes: 0
Views: 5593
Reputation: 2653
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
.
Upvotes: 2
Reputation: 4170
This works for me in 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)
}
but I'd like to see how other libraries like date-fns
implements this conversion which I feel is a very common task
Upvotes: 0