Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is date-fns isAfter and isBefore both false?

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?

like image 334
Ben Avatar asked Oct 18 '25 06:10

Ben


1 Answers

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
like image 102
馬料水碼農 Avatar answered Oct 22 '25 02:10

馬料水碼農