Date fns - rvdegroen/notes GitHub Wiki

Table of contents

What is date-fns?

Date-fns provides a toolset for manipulating Javascript dates in a browser & in Node.js. Date-fns uses the native Date type used in Javascript and comes with functions that you can use in your project, which should make your life easier when working with dates.

Why did we use date-fns?

We used date-fns, so that we could make our life easier when creating the date filter function.

How to use date-fns?

I basically only used differenceInMonths from date-fns, because I wanted to make a filter based on a specific number of months. All I'm doing is comparing the months and using date from the mails as input, to filter the mails.

This is how I implemented it in a different project:


import { differenceInMonths } from "date-fns";

function isNotOlderThanTwoMonths(date) {
  // new Date, gives you the date of right now
  const now = new Date();
  const difference = differenceInMonths(now, date);
  // && both needs to be true, to return true
  return difference >= 0 && difference <= 1;
}

function isBetweenTwoToSixMonthsOld(date) {
  const now = new Date();
  const difference = differenceInMonths(now, date);
  // && both needs to be true, to return true
  return difference >= 2 && difference <= 5;
}

function isBetweenSixToTwelveMonthsOld(date) {
  const now = new Date();
  const difference = differenceInMonths(now, date);
  // && both needs to be true, to return true
  return difference >= 6 && difference <= 11;
}

function isBetweenOneToTwoYearsOld(date) {
  const now = new Date();
  const difference = differenceInMonths(now, date);
  // && both needs to be true, to return true
  return difference >= 12 && difference <= 23;
}

function isOlderThanTwoYears(date) {
  const now = new Date();
  const difference = differenceInMonths(now, date);
  // more than 2 years
  return difference >= 24;
}

Sources