🏠 back to Observable

Data filter for date range

My data (json) has a date field that looks like this:

“occurrencedate”: “2022-01-03 13:05:33 -0500”,

I’m trying to filter it to a range…

viewof start = Inputs.date({label: “Start date”, value: “2021-10-01”})
viewof end = Inputs.date({label: “End date”, value: “2021-12-31”})

data.filter(d => d.occurrencedate >= start && d.occurrencedate <= end)

Nothing ever comes back. I suspect it could be that the data value is not recognized as a Date type (I’m not a JavaScript programmer). I’ve tried adding Data.Parse() which does get some results, but it’s not correct.

data.filter(d => Date.parse(d.occurrencedate) >= Date.parse(start) && Date.parse(d.occurrencedate) <= Date.parse(end))

What’s the correct syntax for the filter?

It seems like you must almost have it!

You’re right that you have to parse the dates when they come from JSON (from which they’ll come as strings). Note that Date.parse returns a number, not a date, but it should be OK because the >= comparison in the filter will turn dates to numbers anyway. Date.parse is used behind-the-scenes when you do new Date("2022-01-03 13:05:33 -0500"), which should usually work, although it has some cross-browser compatibility issues, so you can use d3-time-format for a stricter parser.

Your filter syntax looks good, though you shouldn’t have to parse start and end because Inputs.date already returns a date.

Can you share a link to your notebook, or to a sample notebook that demonstrates the issue? Here’s a working example in case that helps: