1 | # Getting Started
|
2 |
|
3 | ## Table of Contents
|
4 |
|
5 | - [Introduction](#introduction)
|
6 |
|
7 | - [Submodules](#submodules)
|
8 |
|
9 | - [Installation](#installation)
|
10 |
|
11 | ## Introduction
|
12 |
|
13 | **date-fns** provides the most comprehensive, yet simple and consistent toolset
|
14 | for manipulating **JavaScript dates** in **a browser** & **Node.js**.
|
15 |
|
16 | **date-fns** is like [lodash](https://lodash.com) for dates. It has
|
17 | [**140+ functions** for all occasions](https://date-fns.org/docs/).
|
18 |
|
19 | ```js
|
20 | import { format, compareAsc } from 'date-fns'
|
21 |
|
22 | format(new Date(2014, 1, 11), 'MM/dd/yyyy')
|
23 | //=> '02/11/2014'
|
24 |
|
25 | const dates = [new Date(1995, 6, 2), new Date(1987, 1, 11), new Date(1989, 6, 10)]
|
26 | dates.sort(compareAsc)
|
27 | //=> [
|
28 | // Wed Feb 11 1987 00:00:00,
|
29 | // Mon Jul 10 1989 00:00:00,
|
30 | // Sun Jul 02 1995 00:00:00
|
31 | // ]
|
32 | ```
|
33 |
|
34 | ## Submodules
|
35 |
|
36 | **date-fns** includes some optional features as submodules in the npm package.
|
37 | Here is the list of them, in order of nesting:
|
38 |
|
39 | - FP — functional programming-friendly variations of the functions. See [FP Guide](https://date-fns.org/docs/FP-Guide);
|
40 |
|
41 | - UTC (in development) — variations of the functions which calculate dates in UTC±00:00 timezone.
|
42 |
|
43 | The later submodules are also included inside the former if you want to use multiple features from the list.
|
44 |
|
45 | To use submodule features, [install the npm package](#npm) and then import a function from a submodule:
|
46 |
|
47 | ```js
|
48 | // The main submodule:
|
49 | import addDays from 'date-fns/addDays'
|
50 |
|
51 | // FP variation:
|
52 | import addDays from 'date-fns/fp/addDays'
|
53 |
|
54 | // UTC variation:
|
55 | import addDays from 'date-fns/utc/addDays'
|
56 |
|
57 | // Both FP and UTC:
|
58 | import addDays from 'date-fns/fp/utc/addDays'
|
59 |
|
60 | // With tree-shaking enabled:
|
61 | import { addDays, format } from 'date-fns/fp'
|
62 | ```
|
63 |
|
64 | ## Installation
|
65 |
|
66 | The library is available as an [npm package](https://www.npmjs.com/package/date-fns).
|
67 |
|
68 | To install the package, run:
|
69 |
|
70 | ```bash
|
71 | npm install date-fns --save
|
72 | # or
|
73 | yarn add date-fns
|
74 | ```
|
75 |
|
76 | Start using:
|
77 |
|
78 | ```js
|
79 | import { formatDistance, subDays } from 'date-fns'
|
80 |
|
81 | formatDistance(subDays(new Date(), 3), new Date())
|
82 | //=> "3 days ago"
|
83 | ```
|