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

栏目: IT技术 · 发布时间: 4年前

内容简介:But do you know about a library called

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:

Quick Tour of date-fns, a Simple JavaScript Date Library
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!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

大数据经济

大数据经济

谢文 / 北京联合出版公司·后浪出版公司 / 2016-1 / 32.00元

中国互联网数朝元老、中国的“凯文·凯利”首度深度剖析大数据的大机会 大数据纳入中国国家行动方略,大数据产业起飞在即 陈彤、胡舒立、王巍鼎力推荐 ................... ※编辑推荐※ ★ 雅虎中国前总裁、中国互联网第一预言家——谢文,首部大数据力作。本书作者是中国互联网业第一代创业者,历任和讯网总裁、雅虎中国总裁、一起网CEO,亲身经历中国互联网发展全过......一起来看看 《大数据经济》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具