Getting started with Day.js

Published on

Date and time are a regular part of our lives so it's natural that they also appear regularly in our computer programs. You might have a booking system on your website that allows people to select a date and time or a generated transport schedule. This is why JavaScript has a built in Date object to handle managing it.

Although we can achieve a lot with the Date object alone, it's complex and missing key functionality. Luckily there's a lot of third party solutions that solve this problem. One of the most common and mature is Moment.js but it's pretty slow and can significantly increase bundle size. Which is why I instead usually reach for Day.js. Day.js features a similar API to Moment but comes in at only 2Kb and all it's API operations are immutable.

Installation

You can add Day.js to your project by installing the package with either yarn or npm.

Yarn

yarn add dayjs

NPM

npm install dayjs --save

Then to use it you just import it using ES Modules or require it if you're using CommonJS.

ES Modules

import dayjs from 'dayjs';

CommonJS

const dayjs = require('dayjs');

Get Current Date and Time

const now = dayjs();

Parsing Dates

A Day.js object can be initialized by date by passing it a string:

const date = dayjs('2020-07-16');

This string must be given in ISO 8601 format. Here's a handy reference guide:

FormatMeaningExample
YYYY4-digits Year2018
YY2-digits Year18
M2-digits Month number, omits leading 07
MM2-digits Month number07
MMM3-letters Month nameJul
MMMMFull Month nameJuly
ddddFull day nameSunday
gggg4-digits Week year2018
gg2-digits Week year18
wWeek of the year without leading zero18
wwWeek of the year with leading zero18
eDay of the week, starts at 04
D2-digits day number, omits leading 09
DD2-digits day number09
DoDay number with ordinal9th
TIndicates the start of the time part
HH2-digits hours (24 hour time) from 0 to 2322
H2-digits hours (24 hour time) from 0 to 23 without leading 022
kk2-digits hours (24 hour time) from 1 to 2423
k2-digits hours (24 hour time) from 1 to 24 without leading 023
a/Aam or pmpm
hh2-digits hours (12 hour time)11
mm2-digits minutes22
ss2-digits seconds40
s2-digits seconds without leading zero40
S1-digits milliseconds1
SS2-digits milliseconds12
SSS3-digits milliseconds123
ZThe timezone+02:00
xUNIX timestamp in milliseconds1410432140575

Manipulating Dates

You can manipulate dates by adding or subtracting a unit:

const date = dayjs('2020-07-16');

const dayBefore = date.add(1, 'days');
const dayAfter = date.subtract(1, 'days');

The following are valid units:

UnitShorthandDescription
daydDay of Week (Sunday as 0, Saturday as 6)
weekwWeek of Year
monthMMonth (January as 0, December as 11)
quarterQQuarter ( dependent QuarterOfYear plugin )
yearyYear
hourhHour
minutemMinute
secondsSecond
millisecondmsMillisecond

Formatting Dates

Once you're done parsing and manipulating your dates you might have to display or store them in a certain format. In Day.js we can use the handy format method which accepts a string indicating how it should be formatted.

const date = dayjs('2020-07-16');

console.log(date.format());
// "2020-07-16T00:00:00+01:00"

console.log(date.format('DD/MM/YYYY'));
// "16/07/2020"

console.log(date.format('HH:mm'));
// "00:00"

As with parsing dates this string must be in ISO 8601 format

Querying Dates

There are several methods to query a Day.js object. You can find a full list of them in the documentation but here are some I find particularly useful:

const firstDate = dayjs('2020-07-16');
const secondDate = dayjs('2020-07-17');

console.log(firstDate.isBefore(secondDate));
// true

console.log(firstDate.isBefore(secondDate, 'year'));
// false

console.log(firstDate.isAfter(secondDate));
// false

console.log(firstDate.isAfter(secondDate, 'year'));
// false

console.log(firstDate.isSame(secondDate));
// false

console.log(firstDate.isSame(secondDate, 'year'));
// true

Plugins

Another thing I think is great about this library how easily extensible it is. The documentation on how you can go about creating plugins is very clear and because of this many community plugins now exist. These can be anything from generating random dates to support for different calendars.

Shameless plug here are two of mine: Day.js Random Day.js Recur