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

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

内容简介: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!


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

查看所有标签

猜你喜欢:

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

HTTPS权威指南

HTTPS权威指南

[英] Ivan Risti? / 杨洋、李振宇、蒋锷、周辉、陈传文 / 人民邮电出版社 / 2016-9 / 99.00元

本书是集理论、协议细节、漏洞分析、部署建议于一体的详尽Web应用安全指南。书中具体内容包括:密码学基础,TLS协议,PKI体系及其安全性,HTTP和浏览器问题,协议漏洞;最新的攻击形式,如BEAST、CRIME、BREACH、Lucky 13等;详尽的部署建议;如何使用OpenSSL生成密钥和确认信息;如何使用Apache httpd、IIS、Nginx等进行安全配置。一起来看看 《HTTPS权威指南》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具