0

What I want to achieve is, to filter the JSON by past and future events from the current date - like now. My "past" API route should display only the past events, like "id":1 for this example.

Can I do that with, let's say, momentjs and lodash? What would be a correct approach?

This is my JSON array containing the datetime timestamp.

[
    {
        "id": 1,
        "datetime": "2017-08-18T15:15:00+0200",
    },
    {
        "id": 2,
        "datetime": "2020-03-31T10:30:00+0200",
    },
    {
        "id": 3,
        "datetime": "2020-03-31T10:30:00+0200",
    }
]
0

1 Answer 1

1

You can use the Date.parse() method to parse string dates and compare it with current time and filter accordingly as follows:


const data = [
    {
        "id": 1,
        "datetime": "2017-08-18T15:15:00+0200",
    },
    {
        "id": 2,
        "datetime": "2020-03-31T10:30:00+0200",
    },
    {
        "id": 3,
        "datetime": "2020-03-31T10:30:00+0200",
    }
];

const pastDates = data.filter(x => Date.parse(x.datetime) < new Date());

const futureDates = data.filter(x => Date.parse(x.datetime) > new Date());

console.log("Past dates", JSON.stringify(pastDates, null, 4));

console.log("Future dates", JSON.stringify(futureDates, null, 4));

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much and sorry, I didn't notice that this question has already been answered. Linked the original question.