Replace Moment.js with Day.js

CH-K
3 min readFeb 14, 2021
Photo by Fabian Albert on Unsplash

Moment.js is a fantastic time and date library and has been widely used in web development.

However, Moment.js has decided to be a legacy project in maintenance mode. It also encourages people who are going to start a new project may consider other alternative time and date libraries.

From: https://momentjs.com/docs/#/-project-status/

Moment.js has some well-known disadvantages:

There are other alternative time and date libraries, such as Luxon, date-fns, Day.js, etc.

From: https://github.com/you-dont-need/You-Dont-Need-Momentjs#brief-comparison

We have decided to replace Moment.js with Day.js.

From: https://momentjs.com/docs/#/-project-status/

Reasons to choose Day.js:

  • Size (minified size: 6.3KB) is relatively small than Moment.js (minified size: 288.4 KB)
  • Performance of Day.js is faster than of Moment.js (Here are some performance tests)
From: https://inventi.studio/en/blog/why-you-shouldnt-use-moment-js

It’s almost pain-free as sometimes you may just need to replace the word moment() to dayjs() and everything still works fine.

// Moment.js
moment().add(7, 'days');
// output => "2020-08-13T09:12:49.695Z"
moment().subtract(7, 'days');
// output => "2020-07-29T09:12:49.695Z"
// dayjs
dayjs().add(7, 'days');
// output => "2020-08-13T09:12:49.695Z"
dayjs().subtract(7, 'days');
// output => "2020-07-29T09:12:49.695Z"

However, Moment.js is mutable and Day.js is immutable.

// Moment.js
const workHour = moment()
workHour.add(8, 'hours')
// dayjs
let workHour = dayjs()
workHour = workHour.add(8, 'hours')

In this way, this variable workHour is then updated correctly.

Overall, Day.js is a lightweight JavaScript library for manipulating date and time. It supports basic usage, and allows to attach more plugins. If you are not sure which plugins are going to use later, you may start with Day.js and add those plugins if needed.

Furthermore, Day.js is easy to debug as it’s immutable. To make sure a variable is updated correctly, it must be passed back to itself after doing manipulation.

--

--