sayajay.net

formatting a date in javascript, and such

February 16, 2020, 12:00 AM

So, I use a library called fecha, because I am lazy, and also because I don't want to maintain my own date handling code. Ick. I prefer fecha over momentjs for when I don't need all the features of momentjs and just need some simple date formatting.

Install this:

yarn add fecha

Now, for some formatting, because I am definitely too lazy to refer to the doc:

import { format } from 'fecha';

type format = (date: Date, format?: string, i18n?: I18nSettings) => str;

// Custom formats
format(new Date(2015, 10, 20), 'dddd MMMM Do, YYYY'); // 'Friday November 20th, 2015'
format(new Date(1998, 5, 3, 15, 23, 10, 350), 'YYYY-MM-DD hh:mm:ss.SSS A'); // '1998-06-03 03:23:10.350 PM'

// Named masks
format(new Date(2015, 10, 20), 'isoDate'); // '2015-11-20'
format(new Date(2015, 10, 20), 'mediumDate'); // 'Nov 20, 2015'
format(new Date(2015, 10, 20, 3, 2, 1), 'isoDateTime'); // '2015-11-20T03:02:01-05:00'
format(new Date(2015, 2, 10, 5, 30, 20), 'shortTime'); // '05:30'

// Literals
format(new Date(2001, 2, 5, 6, 7, 2, 5), '[on] MM-DD-YYYY [at] HH:mm'); // 'on 03-05-2001 at 06:07'

The one caveat here when working with Unix timestamps:

  • if passing in a Unix timestamp (rather than a date), you have to multiply it by 1000, because it works with milliseconds, rather than seconds.

Yup.