Let me give you an example. This is the accepted answer to a Stack Overflow question asking how to get last day of the month:
var t = new Date(); alert( new Date(t.getFullYear(), t.getMonth() + 1, 0, 23, 59, 59) );
Of course that works, but it’s not immediately obvious what the numbers after
getMonth represent. Now contrast that with the considerably more readable:
const today = new Date(); console.log( lastDayOfMonth(today) );
In this article I’m going to show you how to get up and running with date-fns. After reading you’ll be able to drop it into your projects and take advantage of its many helper methods to manipulate dates with ease. This will make code like
t.getMonth() + 1, 0, 23, 59, 59 a thing of the past.
So, Why Not Just Use Moment.js?
Well, according to Sasha Koss, the creator of date-fns, Moment.js has a few inherent problems which motivated him to create date-fns. Sasha expands on what these problems are on the project’s GitHub page, but in a nutshell:
- Moment.js is mutable which can cause bugs.
- It has a complex OOP API (which doubles the mutability problem).
- It has a performance overhead due to the complex API.
- Its build size is large when used with Webpack, as locale files are included as part of the bundle.
Let’s contrast that with date-fns (taken from the project’s homepage):
- Date-fns is immutable, always returning a new date instead of changing the one you pass in.
- It has a simple API. You always have one function that does one thing.
- It is fast. You can be sure that your users will have the best user experience.
- It is the perfect companion for Webpack. With the function-per-file style you can pick just what you need and stop bloating your project with useless functionality.
For me, the feature that makes it shine is its ease of use. When using it on a web-based project, you can just grab date-fns from a CDN, drop it into your page and profit. More about that next…
There are a variety of ways to install the library.
It’s available as an npm package:
npm install date-fns --save
Or via Yarn:
yarn add date-fns
bower install date-fns
Or from a CDN:
If you chose this method, please note that the library is namespaced under a
dateFns object, in the same way that jQuery is namespaced under
<script> console.log( dateFns.isToday(new Date()) ); </script>
Date-fns Basic Usage
const format = require('date-fns/format'); console.log( format(new Date(2017, 6, 6), 'MM/DD/YYYY') ); // '06/07/2017'
Want to change the locale? No problem: