I know this is a very popular problem, but here goes. So I have an array of records coming in and need to filter them. I am filtering them by date, and I need them to be <=7 and >=1 days from today()s date.
const Today = new Date();
const thirtyday = Today - 30;
const sevenday = Today - 7;
const oneday = Today - 1;
const machinerecords = this.state.tasksnfiltered;
const due = machinerecords.filter(
(record) =>
Date.parse(record.nextdue) <= sevenday &&
Date.parse(record.nextdue) >= oneday
);
{
this.setState({ due: [...due] });
}
I have also tried
machinerecords
.filter((record) => Date.parse(record.nextdue) <= thirtyday)
.filter((record) => Date.parse(record.nextdue) >= sevenday);
The info is coming from a backend I built.
I can get the first filter to run alone accurately for any of the date filters. but cant combine them.
2
Answers
In JavaScript dates have a millisecond representation so your code above is testing for dates between 7 and 1 milliseconds from today so depending on how your reference dates are generated something like the following may work as long as the h/m/s part of your dates are ignorable.
For react though I generally use the date-fns library https://date-fns.org/docs/Getting-Started as its really lightweight compared to momentjs.
date-fns handles ignoring h/m/s issues as well as ‘enough’ timezone handling to be useful.
Most of the filtering logic can exist outside of the component.
Below, I spawned a couple tasks with dates ranging from half a day to ten days.
Only the tasks with a due date within two and five days should be displayed. This can be achieved by comparing two date objects. I assume your
nextdue
date is serialized into a timestamp e.g.YYYY-MM-DD
.Here is a working React (function component) snippet.