Results:
Loading...

Vue Data GridDate Filter

Date Filters allow you to filter date data.

Date Filter

Enabling Date Filters

The Date Filter can be configured as shown below:

<ag-grid-vue
    :columnDefs="columnDefs"
    /* other grid options ... */>
</ag-grid-vue>

this.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:

  • The Date column is using a Date Filter.
  • A Date Filter Comparator is provided to parse the data and allow date comparisons to be made.
  • The minimum valid year is set to 2000, and maximum valid year is 2021. Dates outside this range will be considered invalid, and will:

    • Deactivate the column filter. This avoids the filter getting applied as the user is typing a year - for example suppose the user is typing the year 2008, the filter doesn't execute for values 2, 20 or 200 (as the text 2008 is partially typed).
    • Be highlighted with a red border (default theme) or other theme-appropriate highlight.
  • the inRangeFloatingFilterDateFormat property has been set to define a custom date format, this is only shown in the floating filter panel when an in-range filter has been applied.

Date Filter Parameters

Date Filters are configured though the filterParams attribute of the column definition (IDateFilterParams interface):

browserDatePicker
boolean
Defines whether the grid uses the browser date picker or a plain text box.
  • true: Force the browser date picker to be used.
  • false: Force a plain text box to be used.

  • Default: undefined - If a date component is not provided, then the grid will use the browser date picker for all supported browsers and a plain text box for other browsers.
    buttons
    FilterButtonType[]
    Specifies the buttons to be shown in the filter, in the order they should be displayed in. The options are:
  • 'apply': If the Apply button is present, the filter is only applied after the user hits the Apply button.
  • 'clear': The Clear button will clear the (form) details of the filter without removing any active filters on the column.
  • 'reset': The Reset button will clear the details of the filter and any active filters on that column.
  • 'cancel': The Cancel button will discard any changes that have been made to the filter in the UI, restoring the applied model.
  • buttons: FilterButtonType[];
    
    type FilterButtonType = 
          'apply' 
        | 'clear' 
        | 'reset' 
        | 'cancel'
    
    closeOnApply
    boolean
    If the Apply button is present, the filter popup will be closed immediately when the Apply or Reset button is clicked if this is set to true.
    Default: false
    comparator
    Function
    Required if the data for the column are not native JS Date objects.
    comparator = (
        filterLocalDateAtMidnight: Date,
        cellValue: any
    ) => number;
    debounceMs
    number
    Overrides the default debounce time in milliseconds for the filter. Defaults are:
  • TextFilter and NumberFilter: 500ms. (These filters have text field inputs, so a short delay before the input is formatted and the filtering applied is usually appropriate).
  • DateFilter and SetFilter: 0ms
  • defaultJoinOperator
    JoinOperator
    By default, the two conditions are combined using AND. You can change this default by setting this property. Options: AND, OR
    defaultJoinOperator: JoinOperator;
    
    type JoinOperator = 'AND' | 'OR'
    defaultOption
    string
    The default filter option to be selected.
    filterOptions
    (IFilterOptionDef | ISimpleFilterModelType)[]
    Array of filter options to present to the user. See Filter Options.
    filterOptions: (IFilterOptionDef | ISimpleFilterModelType)[];
    
    interface IFilterOptionDef {
      // A unique key that does not clash with the built-in filter keys. 
      displayKey: string;
      // Display name for the filter. Can be replaced by a locale-specific value using a `localeTextFunc`. 
      displayName: string;
      // Custom filter logic that returns a boolean based on the `filterValues` and `cellValue`. 
      predicate?: (filterValues: any[], cellValue: any) => boolean;
      // Number of inputs to display for this option. Defaults to `1` if unspecified. 
      numberOfInputs?: 0 | 1 | 2;
    }
    
    type ISimpleFilterModelType = 
          'empty' 
        | 'equals' 
        | 'notEqual' 
        | 'lessThan' 
        | 'lessThanOrEqual' 
        | 'greaterThan' 
        | 'greaterThanOrEqual' 
        | 'inRange' 
        | 'contains' 
        | 'notContains' 
        | 'startsWith' 
        | 'endsWith' 
        | 'blank' 
        | 'notBlank'
    
    filterPlaceholder
    FilterPlaceholderFunction | string
    Placeholder text for the filter textbox
    filterPlaceholder: FilterPlaceholderFunction | string;
    
    type FilterPlaceholderFunction = 
          (params: IFilterPlaceholderFunctionParams) => string
    
    
    interface IFilterPlaceholderFunctionParams {
      // The filter option key
      filterOptionKey: ISimpleFilterModelType;
      // The filter option name as localised text
      filterOption: string;
      // The default placeholder text
      placeholder: string;
    }
    
    type ISimpleFilterModelType = 
          'empty' 
        | 'equals' 
        | 'notEqual' 
        | 'lessThan' 
        | 'lessThanOrEqual' 
        | 'greaterThan' 
        | 'greaterThanOrEqual' 
        | 'inRange' 
        | 'contains' 
        | 'notContains' 
        | 'startsWith' 
        | 'endsWith' 
        | 'blank' 
        | 'notBlank'
    
    inRangeFloatingFilterDateFormat
    string
    Defines the date format for the floating filter text when an in range filter has been applied.
    Default: YYYY-MM-DD
    inRangeFloatingFilterDateFormat: string;

    PartTokenOutput
    MonthM1 2 ... 11 12
    Mo1st 2nd ... 11th 12th
    MM01 02 ... 11 12
    MMMJan Feb ... Nov Dec
    MMMMJanuary February ... November December
    Day of MonthD1 2 ... 30 31
    Do1st 2nd ... 30th 31st
    DD01 02 ... 30 31
    Day of Weekd0 1 ... 5 6
    do0th 1st ... 5th 6th
    ddSu Mo ... Fr Sa
    dddSun Mon ... Fri Sat
    ddddSunday Monday ... Friday Saturday
    YearYY70 71 ... 29 30
    YYYY1970 1971 ... 2029 2030
    Y1970 1971 ... 9999 +10000 +10001

    inRangeInclusive
    boolean
    If true, the 'inRange' filter option will include values equal to the start and end of the range.
    includeBlanksInEquals
    boolean
    If true, blank (null or undefined) values will pass the 'equals' filter option.
    includeBlanksInGreaterThan
    boolean
    If true, blank (null or undefined) values will pass the 'greaterThan' and 'greaterThanOrEqual' filter options.
    includeBlanksInLessThan
    boolean
    If true, blank (null or undefined) values will pass the 'lessThan' and 'lessThanOrEqual' filter options.
    includeBlanksInRange
    boolean
    If true, blank (null or undefined) values will pass the 'inRange' filter option.
    maxNumConditions
    number
    Maximum number of conditions allowed in the filter.
    Default: 2
    maxValidYear
    number
    This is the maximum year that may be entered in a date field for the value to be considered valid. Default is no restriction.
    minValidYear
    number
    This is the minimum year that may be entered in a date field for the value to be considered valid.
    Default: 1000
    numAlwaysVisibleConditions
    number
    By default only one condition is shown, and additional conditions are made visible when the previous conditions are entered (up to maxNumConditions). To have more conditions shown by default, set this to the number required. Conditions will be disabled until the previous conditions have been entered. Note that this cannot be greater than maxNumConditions - anything larger will be ignored.
    Default: 1
    readOnly
    boolean
    If set to true, disables controls in the filter to mutate its state. Normally this would be used in conjunction with the Filter API. See Read-only Filter UI.
    Default: false

    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 filterParams.browserDatePicker = true. However, you will need to test this behaviour yourself.

    Date Filter Comparator

    Dates can be represented in your data in many ways e.g. as a JavaScript 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. However, if your date is in any other format you will have to provide your own comparator to perform the date comparisons.

    comparator
    Function
    Required if the data for the column are not native JS Date objects.
    comparator = (
        filterLocalDateAtMidnight: Date,
        cellValue: any
    ) => number;

    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:

    • Any number < 0 if the cell value is less than the filter date.
    • 0 if the dates are the same.
    • Any number > 0 if the cell value is greater than the filter date.

    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.

    <ag-grid-vue
        :columnDefs="columnDefs"
        /* other grid options ... */>
    </ag-grid-vue>
    
    this.columnDefs = [
         // column definition configured to use a date filter
         {
             field: 'date',
             filter: 'agDateColumnFilter',
             // add extra parameters for the date filter
             filterParams: {
                 // provide comparator function
                 comparator: (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;
                 }
             }
         }
     ];

    Once the date comparator callback is provided, then the Date Filter is able to perform all the comparison operations it needs, e.g. 'Less Than', 'Greater Than' and 'Equals'.

    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 Filter Condition is set, this will be a DateFilterModel:

    filterType
    'date'
    Filter type is always 'date'
    dateFrom
    string | null
    The date value(s) associated with the filter. The type is string and format is always YYYY-MM-DD hh:mm:ss e.g. 2019-05-24 00:00:00. Custom filters can have no values (hence both are optional). Range filter has two values (from and to).
    dateTo
    string | null
    Range filter to date value.
    type
    ISimpleFilterModelType | null
    One of the filter options, e.g. 'equals'
    type: ISimpleFilterModelType | null;
    
    type ISimpleFilterModelType = 
          'empty' 
        | 'equals' 
        | 'notEqual' 
        | 'lessThan' 
        | 'lessThanOrEqual' 
        | 'greaterThan' 
        | 'greaterThanOrEqual' 
        | 'inRange' 
        | 'contains' 
        | 'notContains' 
        | 'startsWith' 
        | 'endsWith' 
        | 'blank' 
        | 'notBlank'
    

    If more than one Filter Condition is set, then multiple instances of the model are created and wrapped inside a Combined Model (ICombinedSimpleModel<DateFilterModel>). A Combined Model looks as follows:

    // A filter combining multiple conditions
    interface ICombinedSimpleModel<DateFilterModel> {
        filterType: string;
    
        operator: JoinOperator;
    
        // multiple instances of the Filter Model
        conditions: DateFilterModel[];
    }
    
    type JoinOperator = 'AND' | 'OR';

    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
    const 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 Filter Options to the user.

    The list of options are as follows:

    Option NameOption KeyIncluded by Default
    EqualsequalsYes
    Greater thangreaterThanYes
    Less thanlessThanYes
    Not equalnotEqualYes
    In rangeinRangeYes
    BlankblankYes
    Not blanknotBlankYes
    Choose OneemptyNo

    Note that the empty filter option is primarily used when creating Custom Filter Options. 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 Value Getter, but is specific to the filter.

    filterValueGetter
    string | ValueGetterFunc
    Function or expression. Gets the value for filtering purposes.
    filterValueGetter: string | ValueGetterFunc<TData>;
    
    interface ValueGetterFunc<TData = any> {
        (params: ValueGetterParams<TData>) : any
    }
    
    interface ValueGetterParams<TData = any> {
      // A utility method for getting other column values 
      getValue: (field: string) => any;
      // Row node for the given row 
      node: IRowNode<TData> | null;
      // Data associated with the node 
      data: TData | undefined;
      // Column for this callback 
      column: Column;
      // ColDef provided for this column 
      colDef: ColDef<TData>;
      // The grid api. 
      api: GridApi<TData>;
      // The column api. 
      columnApi: ColumnApi;
      // Application context as set on `gridOptions.context`. 
      context: any;
    }

    Applying the Date Filter

    Applying the Date Filter is described in more detail in the following sections:

    Blank Cells

    If the row data contains blanks (i.e. null or undefined), by default the row won't be included in filter results. To change this, use the filter params includeBlanksInEquals, includeBlanksInLessThan, includeBlanksInGreaterThan and includeBlanksInRange. For example, the code snippet below configures a filter to include null for equals, but not for less than, greater than or in range:

    const filterParams = {
        includeBlanksInEquals: true,
        includeBlanksInLessThan: false,
        includeBlanksInGreaterThan: false,
        includeBlanksInRange: false,
    };

    In the following example you can filter by date and see how blank values are included. Note the following:

    • Column Date has both null and undefined values resulting in blank cells.
    • Toggle the controls on the top to see how includeBlanksInEquals, includeBlanksInLessThan, includeBlanksInGreaterThan and includeBlanksInRange impact the search result.

    Data Updates

    The Date Filter is not affected by data changes. When the grid data is updated, the filter value will remain unchanged and the filter will be re-applied based on the updated data (e.g. the displayed rows will update if necessary).

    Next Up

    Continue to the next section to learn about Set Filters.