Home > Net >  Why is date-fns isAfter and isBefore both false?
Why is date-fns isAfter and isBefore both false?

Time:11-14

I have my current date as

const currentDate = format(new Date(2021, 4, 5), 'yyyy-MM-dd');

Which displays Current Date is: 2021-05-05

Then I have "Manchester's game is ", formatDate('2021-05-04T14:00:00')

The formatDate function is

  const formatDate = (date) => {
    return format(new Date(date), 'yyyy-MM-dd');
  };

Which displays Manchester's game is 2021-05-04

When I compare the two times using isAfter and isBefore, I get false for both.

I am expecting this

console.log(isAfter(currentDate, formatDate('2021-05-04T14:00:00')));

To log true, but it logs false!

Why is that?

CodePudding user response:

The argument type of isAfter is Date | Number, but you put in string type (your formatDate function return string, and currentDate is also string), so it will not work.

const currentDate = new Date(format(new Date(2021, 4, 5), 'yyyy-MM-dd'));
const comparedDate = new Date(format(new Date('2021-05-04T14:00:00'), 'yyyy-MM-dd'));
console.log(currentDate); // Date type
console.log(comparedDate); // Date type

console.log(isAfter(currentDate, comparedDate)); // True
  • Related