DEV Community

Anderson Vilela
Anderson Vilela

Posted on

Why date-fns is an interesting alternative to Moment.js

Moment.js was one of the first libraries to gain notoriety for its ability to parse, format, and calculate dates in a less daunting way for developers. However, nowadays there is an interesting alternative: date-fns.

date-fns is considered a valuable alternative to Moment.js not only because it offers the same set of features, but also because it is attractive to functional programmers. Also, date-fns has a smaller package size compared to Moment.js, which makes it easier to use in projects with size limitations.

Installing date-fns
date-fns can be installed easily using npm or yarn:

Using npm

$ npm install date-fns
Enter fullscreen mode Exit fullscreen mode

Or using yarn

$ yarn add date-fns
Enter fullscreen mode Exit fullscreen mode

formatting dates
Date formatting is the core feature of libraries like Moment.js and date-fns. This is because native JavaScript doesn't have a simple way to handle this.

date-fns uses string patterns similar to Moment.js:

const format = require('date-fns/format');
const stPattysDay = new Date('2020/03/17');
const formattedDate1 = format(stPattysDay, 'MM/dd/yyyy');
const formattedDate2 = format(stPattysDay, 'MMMM dd, yyyy');

console.log(formattedDate1);
// => "03/17/2020"

console.log(formattedDate2);
// => "March 17, 2020"
Enter fullscreen mode Exit fullscreen mode

There are many ways to format dates so they look exactly how you want them.

see more at: https://tablognews.netlify.app/posts/post/por-que-o-date-fns-e-uma-alternativa-interessante-ao-moment-js

Top comments (0)