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:
isValid()
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
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
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
In moment.js, isValid()
is a function within Date object that returns true/false accordingly. Whereas in luxon, isValid
is a Date object property with literal true/false value.
Adding/Subtracting
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
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!