简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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