GollyJer
GollyJer

Reputation: 26662

How to correctly format a postgres timestamp with timezone date using date-fns?

I'm moving from moment to date-fns and need some advice.

I have a postgres timestamp-with-timezone and I'm looking to format it like MAR 2 AT 1:30 PM.

Here is my solution using date-fns.

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

const date = parseISO(message.updated_at); // this is from postgres
const md = format(date, 'MMM d').toUpperCase();
const hm = format(date, 'h:m a');
const formattedTimestamep = `${md} AT ${hm}`;

Is there a more correct or less verbose way?

Upvotes: 0

Views: 5103

Answers (1)

GollyJer
GollyJer

Reputation: 26662

I got an answer over in the date-fns github issues.


There's a small useful sentence in the docs for format.

The characters wrapped between two single quotes characters (') are escaped.


This leads to this more succinct version of the code.

const formattedTimeStamp = format(parseISO(message.updated_at), "MMM d 'AT' h:m a").toUpperCase();

Upvotes: 1

Related Questions