One of the columns in our grid is a date string. Let's try adding a basic filter to the "date opened" column definition:
{
headerName: "Date Opened",
field: "dateOpened",
sortable: true,
filter: "agDateColumnFilter"
},
This won't work, because the ag-Grid date filter is designed for JavaScript Date
objects. What we need to do is add a custom comparator function callback that:
- Converts our strings to
Date
objects - Returns a value less than 0 if the cell value is earlier than the filter date,
- Returns 0 if they are the same, and
- Returns a value greater than 0 if the cell value is greater than the filter date
If this seems familiar (or if it seems very strange), it's because this comparator function works the same way that the compare function used with Array.prototype.sort
does. You can read more about the sort method and compare function to get a little more comfortable with this.
We're also going to set the browserDatePicker
to true
. By default, the grid will use the browser date picker in Chrome and a plain text box for all other browsers. If browserDatePicker
is true, the browser date picker will be used regardless of the browser type.
Here's the finished column definition, including the comparator function:
{
headerName: "Date Opened",
field: "dateOpened",
sortable: true,
filter: "agDateColumnFilter",
filterParams: {
comparator: function(filterLocalDateAtMidnight, cellValue) {
if (cellValue === null) return -1;
let cellDate = new Date(cellValue);
if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
return 0;
}
if (cellDate < filterLocalDateAtMidnight) {
return -1;
}
if (cellDate > filterLocalDateAtMidnight) {
return 1;
}
},
browserDatePicker: true
}
},
When you run npm start
and navigate to localhost:3000, you should be able to filter dates correctly.
Note: Because we are using basic date strings that include time stamps here and no external libraries like Moment.js, you may see some oddities around ranges and other filters. This is due to time zones and localization and not a flaw in ag-Grid. In the real world, you'd most likely use a library like Moment in conjunction with whatever strategy you're using in your database to either normalize for time zones or strip times out altogether. This should happen before ag-Grid even gets those dates in the row data, so it won't affect the implementation shown in this video.
That's how date filters work in ag-Grid. Up next, let's learn about a cool feature called floating filters!