Tutorial

Quick Tour of date-fns, a Simple JavaScript Date Library

Published on March 18, 2020
Default avatar

By William Le

Quick Tour of date-fns, a Simple JavaScript Date Library

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Working with dates in JavaScript isn’t easy. That’s why if you look at the package.json files of most apps, you’ll usually find a library like Moment.js in there.

Moment.js was one of the first libraries to gain notoriety. It made parsing/formatting/calculating dates less daunting for developers.

But do you know about a library called date-fns?

date-fns is generally considered to be a worthy alternative to Moment.js. Not only because it offers the same feature set, but it also appeals to functional programmers.

Install date-fns

You can install date-fns with npm/Yarn:

# Using npm
$ npm install date-fns

# Or using yarn
$ yarn add date-fns

Formatting Dates

Formatting dates is the bread and butter of libraries like Moment.js/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"

It’s that simple! There are lots of ways to format dates so they look exactly the way you want them to.

Adding/Subtracting Dates

Now that we can format dates, what about performing addition/subtractions with them? There are several functions for doing this:

In the example below, we add 1 year to a specified date:

const format = require('date-fns/format');
const addYears = require('date-fns/addYears');

const stPattysDay = new Date('2020/03/17');
const stPattysDayNextYear = addYears(stPattysDay, 1);
const formattedDate = format(stPattysDayNextYear, 'MMMM dd, yyyy');

console.log(formattedDate);
// => "March 17, 2021"

Using Locales

Formatting is pretty easy, but what about locales? We know that users will be visiting your website from around the world, and we don’t want to assume they speak our native language.

For this, we can import specific locale plugins:

const format =  require('date-fns/format');
const russianLocale = require('date-fns/locale/ru');

const stPattysDay = new Date('2020/03/17');
const formattedDate = format(stPattysDay, 'MMMM dd, yyyy', { locale: russianLocale });

console.log(formattedDate);
// => "марта 17, 2020"

Differences Between 2 Dates

The ability to calculate the differences between 2 dates is important for a date manipulation library. date-fns provides several functions for calculating this.

For example, we can calculate the days from January 1st to Christmas (as well as “business days”!):

const format = require('date-fns/format');
const addYears = require('date-fns/addYears');
const differenceInDays = require('date-fns/differenceInDays');
const differenceInBusinessDays = require('date-fns/differenceInBusinessDays')

const startDate = new Date('2020/01/01');
const endDate = new Date('2020/12/24');
const daysBetween = differenceInDays(endDate, startDate);
const workdaysBetween = differenceInBusinessDays(endDate, startDate);

console.log(daysBetween);
// => 358

console.log(workdaysBetween);
// => 256

🎁 Bonus! date-fns has a Small Footprint 🎁

One of the biggest downsides to using Moment.js is that it’s large! There isn’t a way to import individual functions because its API only allows for chaining. This means you’re required to import the entire library:

const moment = require('moment');
const formattedDate = moment(new Date()).format('MM/DD/YYYY');

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

With date-fns, you only grab the specific functions you need (a lot like with Lodash):

const format = require('date-fns/format');
const formattedDate = format(new Date(), 'MM/dd/yyyy');

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

This makes date-fns a much smaller dependency than Moment.js. See the graphic below for the bundle sizes of Moment.js vs date-fns:

bundle size comparison moment.js vs date-fns

Source: BundlePhobia

Note that there’s a way to configure webpack to exclude the “locale” plugins. This would significantly reduce its bundle size.

Conclusion

date-fns seems to be getting a lot more development work than Moment.js at the moment 😉. For this reason, it’s really well-maintained, and developers get more input into its direction. Along with its robust feature set and modern ES6 sensibilities, it’s worth giving it a try! 📅📌

The official docs for date-fns are really great, and have lots of code samples!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
William Le

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel