Migrating from Moment.js to Luxon

In this article, I will mention some of the most commonly used features of moment.js and provide the luxon alternative of those features along with documentation links.

I must confess, I initially thought dayjs to be a better alternate to moment.js as the syntaxes are identical but after implementing it first hand, I personally found dayjs to be finicky and inconsistent. Some of the reasons being:

  • incorrectly returns true for an invalid date when moment used to return false (probably fixed in recent versions).
  • Not able to parse both “3” and “03” to DD format consistently whereas moment could.
  • Didn't like the way dayjs extends various plugins, looks odd to have 3+ LOC just to declare a library feature.

In spite of my initial reluctance for luxon, I quickly noticed how intuitive and convenient it was to migrate from moment.js. So, lets do this!

Parsing

Docs, API docs

This is one of my most commonly used feature and usually the first step if you are using a lot of user entered dates, which you would have to parse into a Date object to run further logic on them.

Formatting

Docs, API docs

This is one of my other most commonly used feature. I use this to convert a Date object into say “2022–03–20” string format for the DB. Also, to convert a DB returned date into “3 March 2022” string format for the view.

Validity

Docs, API docs

In moment.js, is a function within Date object that returns true/false accordingly. Whereas in luxon, is a Date object property with literal true/false value.

Adding/Subtracting

Docs, API docs

Comparison

Docs, No APIs needed

IsBetween

There is a useful function in moment.js named isBetween, to basically check if a datetime is between two datetimes. You can now easily, accurately do the same on luxon as well.

Difference

Docs, API docs

I use this to check if a date is a future date or not (for my use case, future counting from the next day).

Conclusion

Hope you found this article helpful!

--

--

Experienced Full-Stack Developer who loves sharing knowledge. Gaming & Music addict. Always grateful and looking for new experiences in life.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikhil Nanjappa

Experienced Full-Stack Developer who loves sharing knowledge. Gaming & Music addict. Always grateful and looking for new experiences in life.