Home > other >  React - getting error when filter array of dates
React - getting error when filter array of dates

Time:05-23

This gives me a array of createdAt timestamps like: ['2022-05-22T21:57:45.202Z', '2022-05-22T21:57:45.205Z']

 const unpaid = feeStatus.map((date) => {
    return date.createdAt;
  });

Now i wanna try to filter the array and show only those dates that are older than 14 days:

unpaid.filter(
    (test) => new Date().getTime() - test.getTime() / (1000 * 60 * 60 * 24) > 14
  );

But im getting this error: Uncaught TypeError: test.getTime is not a function

CodePudding user response:

First of all, the getTime() function is a method of the Date object. So you will need to convert the strings to valid Date objects. e.g. new Date(str), or using a library to handle it, like date-fns.

Secondly, there is a group of brackets missing from your formula. It should be:

(new Date().getTime() - new Date(test)) / (1000 * 60 * 60 * 24) > 14.

References:

CodePudding user response:

You need to cast a string format date to Date to be able to use its prototype methods:

unpaid.filter(
    (test) => new Date().getTime() - new Date(test).getTime() / (1000 * 60 * 60 * 24) > 14
  );
  • Related