Krishna Gediya
Krishna Gediya

Reputation: 11

Column sorting issue in date field with dd/MM/YYYY format in angular ig-grid

In igx-grid,

  1. When we apply sorting in ascending and descending order with dd-mm-yyyy format, so sorting is not working with actual date, month and year wise. and only apply date wise sorting.

  2. When we apply sorting in ascending and descending order the date filed it is sorted by yyyy-mm-dd format and we display date in dd/MM/yyyy format on UI using pipe. So sorting is not working in this case.

Upvotes: 1

Views: 1649

Answers (2)

Faizan Saiyed
Faizan Saiyed

Reputation: 852

You can use comparator function of Ag-Grid as follows:

 {
      field: 'invoiceDate',
      valueGetter: e => {
        return this.datePipe.transform(e.data.invoiceDate, 'dd/MM/yyyy');
      },
      comparator: this.dateComparator.bind(this)
    },

and comparator function:

dateComparator(date1, date2) {
    var date1Number = date1 && moment(date1, 'DD/MM/YYYY').toDate().getTime();
    var date2Number = date2 && moment(date2, 'DD/MM/YYYY').toDate().getTime();

    if (date1Number == null && date2Number == null) {
      return 0;
    }

    if (date1Number == null) {
      return -1;
    } else if (date2Number == null) {
      return 1;
    }

    return date1Number - date2Number;
}

This will compare two dates by EPOCH time

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

If you haven't applied [dataType]="'date'" to the grid column, then the type defaults to string and column values will be sorted as strings. Add the correct dataType and sorting will work on the dates, regardless of formatting.

Upvotes: 2

Related Questions