Date-fns: Quick sanity check as I move from moment.js.

Created on 2 Mar 2020  路  3Comments  路  Source: date-fns/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?


cross-post 馃憞
https://stackoverflow.com/questions/60496983/how-to-correctly-format-a-postgres-timestamp-with-timezone-date-using-date-fns

Most helpful comment

Hmm, how about this? From the docs (https://date-fns.org/v2.10.0/docs/format):

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

So, we can do this:

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

Runkit test (https://npm.runkit.com/date-fns):

image

Let me know if it doesn't match your requirement!

All 3 comments

Hmm, how about this? From the docs (https://date-fns.org/v2.10.0/docs/format):

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

So, we can do this:

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

Runkit test (https://npm.runkit.com/date-fns):

image

Let me know if it doesn't match your requirement!

@Imballinst Thanks! That works perfectly.

I read the whole docs section on format, even that exact line, but it didn't quite register.

Thanks again. Super helpful. 馃憤

@GollyJer you're welcome! I'm glad to be able to help 馃槃

Was this page helpful?
0 / 5 - 0 ratings

Related issues

djleonskennedy picture djleonskennedy  路  3Comments

amazing-gao picture amazing-gao  路  3Comments

duro picture duro  路  3Comments

lukewlms picture lukewlms  路  3Comments

suvash picture suvash  路  3Comments