0

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"
  }
]

2 Answers2

0

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.split('/')[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.

OttherCreek
  • 615
  • 1
  • 6
  • 18
  • 1
    *Array.prototype.at* is experimental so there should be a warning about that. Re `json.date_posted.string('/')[0]`, there is no *String.prototype.string*, perhaps you meant *split*? – RobG Jan 19 '22 at 02:16
0

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);
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • `new Date(`${year}-${month}-${day}` will treat the values as UTC (not to mention the inefficiency of parsing a string to create another string that is parsed by the built–in parser). Since you've already got the values, consider `new Date(year, month-1, day)`. :-) In regard to subtracting days, there are issues with using multiples of 8.64e7 and local dates, see [*How to subtract days from a plain Date?*](https://stackoverflow.com/questions/1296358/how-to-subtract-days-from-a-plain-date) – RobG Jan 19 '22 at 02:21