How to get the difference between dates using date fns

366 Views Asked by At

I am trying to get the difference between two dates using date fns, but the result is NaN.

import { format, differenceInCalendarDays, parseISO, formatDistance } from "date-fns";
import { ru } from 'date-fns/locale';

export function getCurrentDate() {
  const date = new Date();
  const pattern = `PPp`;
  return format(date, pattern, {locale: ru});
}

export function getDifferenceDate(startDate, endDate) {
  const start = startDate;
  const end = endDate;

  console.log(start, end)
  return differenceInCalendarDays(start, end);
}

1

There are 1 best solutions below

0
mandy8055 On

Based on the provided information; you will need to parse the input dates before passing them to differenceInCalendarDays function. Something like:

import { format, differenceInCalendarDays, parseISO, formatDistance } from "date-fns";
import { ru } from 'date-fns/locale';

export function getCurrentDate() {
  const date = new Date();
  const pattern = `PPp`;
  return format(date, pattern, {locale: ru});
}

export function getDifferenceDate(startDate, endDate) {
  const start = parseISO(startDate); // <--- Notice this
  const end = parseISO(endDate); // <--- Notice this

  console.log(start, end)
  return differenceInCalendarDays(start, end);
}

CODE DEMO