Date Filters

Date Filters allow you to filter date data.

Filter UI

Enabling Date Filters

The Date Filter can be configured as shown below:

columnDefs = [
    {
        'field': 'date',
        # configure column to use the Date Filter
        'filter': 'agDateColumnFilter',
        'filterParams': {
            # pass in additional parameters to the Date Filter
        },
    },
]

Example: Date Filter

The example below shows the date filter in action, using some of the configuration options discussed below.

Note that in order for the date filtering and sorting to work “out of the box”, the date must either be a JavaScript
Date object, or a string date in the format “yyyy-mm-dd”

In the “Date” column:

In the “Date (date object)” column:

In the “Date (yyyy-mm-dd)” column:

import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)
df["date_string"] = pd.to_datetime(df['date'], infer_datetime_format=True).dt.strftime('%Y-%m-%d')

columnDefs = [
    {"field": "athlete"},
    {"field": "country"},
    {
        "field": "date",
        "filter": "agDateColumnFilter",
        "filterValueGetter": {"function": "d3.timeParse('%d/%m/%Y')(params.data.date)"},
        "filterParams": {
            "browserDatePicker": True,
            "minValidYear": 2000,
            "maxValidYear": 2021,
        },
    },
    {
        "headerName": "Date (date object)",
        "filter": "agDateColumnFilter",
        "valueGetter": {"function": "d3.timeParse('%d/%m/%Y')(params.data.date)"},
        "valueFormatter": {"function": "params.data.date"},
    },
    {
        "field": "date_string",
        "headerName": "Date (yyyy-mm-dd)",
        "filter": "agDateColumnFilter",
        "editable": True
    },
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="date-filter-example",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            defaultColDef={"flex": 1, "minWidth": 150, "floatingFilter": True},
            dashGridOptions={"animateRows": False}
        ),
    ],
)

if __name__ == "__main__":
    app.run(debug=True)

Date Filter Parameters

Date Filters are configured though the filterParams attribute of the column definition:

Date Selection Component

By default, the grid will use the browser-provided date picker for
all Supported Browsers, but for other browsers it
will provide a simple text field. To override this and provide a custom date picker,
see Date Component.

It is also possible to enable a native date picker for unsupported browsers by setting browserDatePicker=True in
the filterParams. However, you will need to test this behaviour yourself.

Converting Dates

Dates can be represented in your data in many ways, for example, as a Date object, as a string in a particular format
such as '26-MAR-2020', or something else. How you represent dates will be particular to your application.

By default, the date filter assumes you are using JavaScript Date objects. If this is the case, the date filter will
work out of the box. If your date is a string, you can use d3.timeParse to create a JavaScript Date object from a
string. See more info in the D3 Value Formatters section.

date_obj = "d3.timeParse(<specifier>)(<date_string>)"

For example, if you had a column with a date field, here are ways to create a date object based on the date string:

# date string "2023-01-30"
date_obj = "d3.timeParse('%Y-%m-%d')(data.date)"

# date string "Sun Jan 01, 2023"
date_obj = "d3.timeParse(%a %b %d, %Y')(data.date)"

To see the specifiers and examples of displaying dates in various formats please see
the D3 Value Formatters section.

Note - the filter works for dates only, not datetime. So if your date string looks like “2023-01-01T22:00:00” you will
first need to change it to date string, for example “2023-01-01”

The first example above demonstrates how to convert
strings to date objects in the valueGetter and filterValueGetter props.

Date Filter Comparator

Another option for the date filter is to create your own comparator to perform the date comparisons.

The comparator function takes two parameters. The first parameter is a JavaScript Date object for the selected date
in the filter (with the time set to midnight). The second parameter is the current value of the cell in the row being
evaluated. The function must return:

This pattern is intended to be similar to the JavaScript compareTo(a, b) function.

Below is an example of using a date filter with a comparator.

Example: Date Comparator

View the JavaScript functions used for this example

These JavaScript functions must be added to the dashAgGridFunctions.js file in the assets folder.
See JavaScript Functions
for more information.

var dagfuncs = (window.dashAgGridFunctions = window.dashAgGridFunctions || {});

dagfuncs.dateFilterComparator = (filterLocalDateAtMidnight, cellValue) => {
    const dateAsString = cellValue;

    if (dateAsString == null) {
        return 0;
    }

    // In the example application, dates are stored as dd/mm/yyyy
    // We create a Date object for comparison against the filter date
    const dateParts = dateAsString.split("/");
    const year = Number(dateParts[2]);
    const month = Number(dateParts[1]) - 1;
    const day = Number(dateParts[0]);
    const cellDate = new Date(year, month, day);

    // Now that both parameters are Date objects, we can compare
    if (cellDate < filterLocalDateAtMidnight) {
        return -1;
    } else if (cellDate > filterLocalDateAtMidnight) {
        return 1;
    }
    return 0;
};
import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

columnDefs = [
    {"field": "athlete"},
    {"field": "country"},
    {
        "field": "date",
        "filter": "agDateColumnFilter",
        "filterParams": {
            "comparator": {"function": "dateFilterComparator"},
            "browserDatePicker": True,
            "minValidYear": 2000,
            "maxValidYear": 2021,
        },
    },
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="date-filter-comparator",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            defaultColDef={"flex": 1, "minWidth": 150, "floatingFilter": True},
            dashGridOptions={"animateRows": False}
        ),
    ],
)

if __name__ == "__main__":
    app.run(debug=True)

More Filter Examples:
- Filter Condition (last 3 examples)
- Filter Options (first example)
- Custom Filter Options (Example 2 sorting dates)

Date Model vs Comparison Types

It should be noted that the Date Filter Model represents the Date as a string in format 'YYYY-MM-DD', however when
doing comparisons the date is provided as a JavaScript Date object as that’s what date pickers typically work with.
The model uses string representation to make it easier to save and avoid any timezone issues.

Date Filter Model

The Filter Model describes the current state of the applied Date Filter. If only
one Value Getter is set, this will be
a DateFilterModel:

If more than one Filter Condition is set, then multiple instances of the model are created and wrapped inside a Combined
Model.

Note that in AG Grid versions prior to 29.2, only two Filter Conditions were supported. These appeared in the Combined
Model as properties condition1 and condition2. The grid will still accept and supply models using these properties,
but this behaviour is deprecated. The conditions property should be used instead.

An example of a Filter Model with two conditions is as follows:

# Date Filter with two conditions, both are equals type
dateEquals04OrEquals08 = {
    'filterType': 'date',
    'operator': 'OR',
    'conditions': [
        {
            'filterType': 'date',
            'type': 'equals',
            'dateFrom': '2004-08-29'
        },
        {
            'filterType': 'date',
            'type': 'equals',
            'dateFrom': '2008-08-24'
        }
    ]
}

Date Filter Options

The Date Filter presents a list
of first example to the user.

The list of options are as follows:

Option Name Option Key Included by Default
Equals equals Yes
Does not equal notEqual Yes
Before lessThan Yes
After greaterThan Yes
Between inRange Yes
Blank blank Yes
Not blank notBlank Yes
Choose one empty No

Note that the empty filter option is primarily used when
creating Applying Filters.
When ‘Choose one’ is displayed, the filter is not active.

The default option for the Date Filter is equals.

Date Filter Values

By default, the values supplied to the Date Filter are retrieved from the data based on the field attribute. This can
be overridden by providing a filterValueGetter in the Column Definition. This is similar to using
a