9

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

 4 years ago
source link: https://alligator.io/js/date-fns/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Working with dates in JavaScript isn’t easy. That’s why if you look at thepackage.json files of most apps, you’ll usually find a library likeMoment.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

— Sorry to interrupt this program!

If you're interested in learning JavaScript in a comprehensive and structured way, I highly recommend you try Wes Bos' Beginner JavaScript or ES6+ for Everyone course. Learning from a premium course like that is a serious investment in yourself.

Plus, these areaffiliate links, so if you purchase a course you help Alligator.io continue to exist at the same time! :pray:

- Seb, :v:+:heart:

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

:gift: Bonus! date-fns has a Small Footprint :gift:

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:

mYrm6bI.png!web 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 :wink:. 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! :date::pushpin:

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK