Fixed old post. I am looking for clues and solutions that can help me get all the records in the JSON array from the past 30 days (based on the date_post field dd/mm/yyyy).
I have used getMonth() but I am getting an unexpected output due to the format mismatch. Is there a way to do this without having to swap dd and mm?
[
{
"id": "5537a23050b2c722f390ab60",
"thumbImage": "http://lorempixel.com/175/115",
"title": "reprehenderit nisi occaecat magna eiusmod officia qui do est culpa",
"date_posted": "19/04/2020"
}
]
CodePudding user response:
Can't you simply write a loop, that iterates over your JSON array and checks whether the date is younger than 30 days?
Like so:
var currentDay=getDay(jsonArr.at(-1));
var currentMonth=getMonth(jsonArr.at(-1));
var lastEntries=[];
foreach(jsonArr => json){
if(getDay(json) < currentDay && getMonth(json) == currentMonth ||
getDay(json) > currentDay && getMonth(json) < currentMonth){
lastEntries[]=json;
}
And now you just have to implement the functions getDay() and getMonth():
function getDay(json){
return json.date_posted.string('/')[0]; // and for the getMonth() function you take the [1] instead of [0]
}
This solution is not very clean and nice, but it should work.
CodePudding user response:
You'll need to parse the date and then use Array.filter (or something like that). Here is one example:
const data = [
{
"id": "5537a23050b2c722f390ab60",
"thumbImage": "http://lorempixel.com/175/115",
"title": "reprehenderit nisi occaecat magna eiusmod officia qui do est culpa",
"date_posted": "19/04/2020"
},
{ "id": "2", "date_posted": "19/04/2021"},
{ "id": "2", "date_posted": "19/01/2019"},
{ "id": "2", "date_posted": "07/01/2022"},
];
const threshold = Date.now() - 30 * 24* 60 * 60 * 1000;
const filtered = data.filter(({date_posted}) => {
const [day, month, year] = date_posted.split('/');
return (new Date(`${year}-${month}-${day}`)) > threshold;
});
console.log(filtered);
