Date Formatting with Day.js
A Lightweight Library for TypeScript Projects
Date handling is one of those things that seems simple until it isn't. I've been using Day.js on a few TypeScript projects lately, and it's become my go-to for anything date-related. At around 2KB gzipped, it's tiny compared to alternatives, and the API is clean enough that I rarely need to check the docs.

Day.js has a few things going for it beyond just size. Operations are immutable, so you won't accidentally mutate a date object somewhere and spend an hour tracking down the bug. It uses a plugin architecture, so you only load what you need. And if you've used Moment.js before, the API will feel familiar.
Setting Up
Getting started takes just a couple of npm commands:
npm init -y
npm install dayjs
npm install --save-dev typescript ts-node @types/node
npx tsc --init
Formatting Dates
The format() function is where you'll spend most of your time. You pass it a string of tokens, and it returns the formatted date:
const date = dayjs('2021-09-16T14:30:00Z');
// Full format: Saturday, September 16, 2021
console.log(date.format('dddd, MMMM D, YYYY'));
// Compact: 09/16/21
console.log(date.format('MM/DD/YY'));
// Time in 12-hour format: 02:30:00 PM
console.log(date.format('hh:mm:ss A'));
// Time in 24-hour format: 14:30
console.log(date.format('HH:mm'));
The tokens are intuitive once you learn a few: YYYY for four-digit year, MM for two-digit month, DD for day, HH for 24-hour time, hh for 12-hour. The Day.js docs have the full list.
Parsing Different Formats
Day.js handles parsing from various formats without much fuss:
// ISO format
const isoDate = dayjs('2021-09-16T14:30:00Z');
console.log(isoDate.format('YYYY-MM-DD')); // 2021-09-16
// Compact format with custom pattern
const compactDate = dayjs('20210916', 'YYYYMMDD');
console.log(compactDate.format('DD/MM/YYYY')); // 16/09/2021
// Textual month
const textualDate = dayjs('16 September 2021', 'DD MMMM YYYY');
console.log(textualDate.format('YYYY-MM-DD')); // 2021-09-16
Locale Support
Need dates in another language? Day.js supports locale switching:
import 'dayjs/locale/fr';
const date = dayjs('2021-09-16');
console.log(date.locale('fr').format('dddd, D MMMM YYYY'));
// samedi, 16 septembre 2021
Unix Timestamps
Working with Unix timestamps is straightforward:
// Parse a Unix timestamp
const unixDate = dayjs.unix(1631804400);
console.log(unixDate.format('YYYY-MM-DD')); // 2021-09-16
// Convert a date to Unix timestamp
const timestamp = dayjs('2021-09-16').unix();
console.log(timestamp); // 1631750400
Day.js also has plugins for relative time ("3 days ago"), timezone handling, and duration formatting. I've found that for most projects, the core library plus maybe one or two plugins covers everything I need without pulling in extra weight.