Se corrigió la publicación anterior . Estoy buscando pistas y soluciones que puedan ayudarme a obtener todos los registros en la matriz JSON de los últimos 30 días (según el campo date_post dd/mm/yyyy ).
He usado getMonth() pero obtengo un resultado inesperado debido a la falta de coincidencia de formato. ¿Hay alguna manera de hacer esto sin tener que intercambiar dd y 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" } ]¿No puede simplemente escribir un ciclo, que itere sobre su matriz JSON y verifique si la fecha es anterior a 30 días?
Al igual que:
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; } Y ahora solo tienes que implementar las funciones getDay() y getMonth() :
function getDay(json){ return json.date_posted.split('/')[0]; // and for the getMonth() function you take the [1] instead of [0] }Esta solución no es muy limpia y agradable, pero debería funcionar.
Deberá analizar la fecha y luego usar Array.filter (o algo así). Aquí hay un ejemplo:
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);