Date-fns is a modern JavaScript date utility library which provides a comprehensive yet consistent toolset for manipulating JavaScript dates in both the browser and Node.js. This robust library is comparable to Lodash but specifically designed for date-related tasks. With over 200 functions for various needs, date-fns allows you to pick and use only what you require. This modular structure works seamlessly with webpack, Browserify, or Rollup and fully supports tree-shaking. Date-fns uses existing native date types and is built using pure functions, maintaining both immutability and safety by always returning a new date instance. Furthermore, this library fully supports TypeScript and Flow and offers extensive localization with dozens of locales included, giving users the ability to add only what they need.
Using date-fns is made straightforward by its intuitive and user-friendly design. To get started, you first need to add date-fns to your project by executing npm install date-fns --save
for npm or yarn add date-fns
for yarn in your terminal. Once installed, you can import the specific functions you need from date-fns into your JavaScript code. Here's an example:
import { compareAsc, format } from 'date-fns'
format(new Date(2014, 1, 11), 'yyyy-MM-dd')
//=> '2014-02-11'
const dates = [
new Date(1995, 6, 2),
new Date(1987, 1, 11),
new Date(1989, 6, 10),
]
dates.sort(compareAsc)
//=> [
// Wed Feb 11 1987 00:00:00,
// Mon Jul 10 1989 00:00:00,
// Sun Jul 02 1995 00:00:00
// ]
In this example, we import the compareAsc
and format
functions and use them to format a date and sort an array of dates, respectively.
Comprehensive documentation for date-fns is available, which provides in-depth and valuable information on how to get started with the library, as well as its vast API and various other related documents. To access the date-fns documentation, simply visit date-fns.org and click the 'Documentation' link or directly access the Getting Started guide at date-fns.org docs.