how to use the eachyearofinterval function from date-fns in javascript

To use the eachYearOfInterval function from date-fns library, follow these steps:

  1. Install date-fns using npm
index.tsx
npm install date-fns
21 chars
2 lines
  1. Import the eachYearOfInterval function from date-fns
index.tsx
import { eachYearOfInterval } from 'date-fns';
// or
const { eachYearOfInterval } = require('date-fns');
105 chars
4 lines
  1. Pass a date interval range to the eachYearOfInterval function
index.tsx
const start = new Date('2020-01-01')
const end = new Date('2022-01-01')

const years = eachYearOfInterval({ start, end });
console.log(years);

// Output: [ 2020, 2021 ]
170 chars
8 lines

The eachYearOfInterval function returns an array of each year between the start and end date passed in as an object with start and end properties. In the example above, it returns [ 2020, 2021 ].

You can now use the eachYearOfInterval function to get an array of years for any given date interval range.

gistlibby LogSnag