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.
Moment.js has some well-known disadvantages:
- It is highly based on OOP APIs, which makes it fail to work with tree-shaking, thus leading to a huge bundle size and performance issues.
- Its complex OOP API doubles mutability problem and causes bugs: https://github.com/moment/moment/blob/develop/src/test/moment/add_subtract.js#L244-L286
There are other alternative time and date libraries, such as Luxon, date-fns, Day.js, etc.
We have decided to replace Moment.js with Day.js.
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)
- Codes are similar. It’s almost pain-free to switch from Moment.js to Day.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.