JavaScript Date is no fun! It's OK for the basics, but once you want to do more complex manipulations, you have to go back and forth from milliseconds (number) to Date. It makes our code less readable and coding more tedious.
Moment.js was my go-to library for everything that has to do with dates. JavaScript date format, adding or subtracting time, converting between timezones, and many more. Momentjs has its drawbacks, but it was a great tool. Unfortunately, the team decided to declare that it's now in maintenance mode and is considered a legacy project. It means only one thing we have to look for alternatives.
Recently, I started using date-fns, and I like it! date-fns is a set of utility functions for JavaScript dates. Unlike moment, date-fns uses the Date object and doesn't create a new object to encapsulate it.
Second, it's genuinely a set of functions. You import whatever functions you want and use them with the Date objects. Yes, yes, you got it right, tree-shaking out-of-the-box! Your production bundle will include only the functions you export and used.
On their website, they mention a few more perks, which are fantastic! Typescript support, immutable by default, consistent with timezones, internationalization & localization support (with tree-shaking as well!), and more goodies.
The community is already pretty big with 181 contributors, including financial contributors, among them you can also find Addy Osmani.
Coding time!
Please note that we import only functions and provide them with a regular js date object.
To achieve the same with moment.js:
This time we have to import the moment function, which creates a new object with all momentjs functionality. It means no tree-shake, and we cannot use js date object. We must convert it to a momentjs object first.
I think that's all you need to know to give it a try and see if you like it.
โ
P.S
I want to thank the moment.js team from the bottom of my heart! โค๏ธ