Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Date/Time column in angular 4 material sort?

I'm using angular material table and using matSort for sorting. But it's not sorting the dates/time column. It takes the datetime column values as strings.

How to sort date/time column in angular 4 material ?

My json will look like this

 {
        "name": "Rule Test 5",
        "time": "2017-11-17T08:34:32",
        "version": 1,
        "status": "SAVED"
    }, {
        "name": "Availability Adjustment",
        "time": "2017-11-17T10:13:27",
        "version": 1,
        "status": "SAVED"
    }, {
        "name": "Class suppression",
        "time": "2017-11-17T11:18:44",
        "version": 1,
        "status": "SAVED"
    }

my table look like this

-------------------------------
name | version | status | date |
-------------------------------
...
..
..
--------------------------------
like image 723
Munna Avatar asked Nov 27 '17 08:11

Munna


People also ask

How do you sort dates in a material table?

Here is the solution:- Pass Date object in sortingDataAccessor function which will make sure date objects will get sorted correctly. this. dataSource. sortingDataAccessor = (item, property) => { switch (property) { case 'fromDate': return new Date(item.

How do I sort dataset by date?

Here's how to sort unsorted dates: Drag down the column to select the dates you want to sort. Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

What is matSort?

The <mat-sort-header> and matSort, an Angular Directives, are used to add sorting capability to a table header.


1 Answers

Here is solution:

this.dataSource.sortingDataAccessor = (item, property): string | number => {
  switch (property) {
    case 'fromDate': return new Date(item.fromDate).toNumber();
    default: return item[property];
  }
};

MatTableDataSource has sortingDataAccessor which we can customize as per our need.

like image 167
Sagar Kharche Avatar answered Oct 03 '22 10:10

Sagar Kharche