Reputation: 1122
I am now try to filter the data sending back to the user,
I am filtering by the date, month & year.
I got the date and month correct but the year is giving me strange result
here is my code
const filterByDate = (req) => {
const match = {
shop_id: req.params.shop_id,
};
let beforeString, afterString, date, filter_by, params;
if (filter_by == "date") {
beforeString = date;
afterString = new Date(date.getTime() + 86400000);
} else if(filter_by == "month") {
beforeString = new Date(date.setDate(1));
afterString = new Date(date.getFullYear(), date.getMonth() + 1, 1);
}else if(filter_by == "year"){
beforeString = new Date(date.setDate(1));
afterString = new Date(date.getFullYear(), date.getYear(), 1);
console.log(afterString)
}
match.createdAt = {
$gte: moment(beforeString, "YYYY/MM/DD"),
$lt: moment(afterString, "YYYY/MM/DD"),
};
return match
};
As you can see I am console.logging the afterString
inside the else if
loop whenever i try to call the route.
The date its giving me back is in 2031
instead of 2021
This happen only in the else if year
filter
here is the console.log statement
2031-01-31T17:00:00.000Z
2031-01-31T17:00:00.000Z
Here is the route I am calling with date
/incomes/?filter_by=year&date=2021/07/04
Upvotes: 0
Views: 147
Reputation: 22247
The params for new Date
are
new Date(year, monthIndex, day)
In the second else if, for monthIndex, you are passing in date.getYear() instead of a month value.
Upvotes: 1