Fabian
Fabian

Reputation: 289

Cannot sort date of birth using datetime with moment plugin in angular 2 projects

I have a table that displays id, name, and date of birth as below:

<table id="example" class="display nowrap" style="width:100%">
  <tr>
    <td>id</td>
    <td>name</td>
    <td>date of birth</td>
  </tr>
  <tr *ngFor="let item of items">
    <td>{{ item.id }}</td>
    <td>{{ item.name }}</td>
    <td>{{ item.dob }}</td>
  </tr>
</table>

And I have the following codes to display the data table:

declare const $;
export class Sampleomponent implements OnInit {

items: any[] = [
{ 'id': 1, 'name': 'sample1', "dob": '1900-01-01T05:00:00'  },
{ 'id': 2, 'name': 'sample2', "dob": '1937-10-11T05:00:00'  },
{ 'id': 3, 'name': 'sample3', "dob": '1954-02-01T05:00:00'  },
{ 'id': 4, 'name': 'sample4', "dob": '1940-12-01T05:00:00'  },
{ 'id': 5, 'name': 'sample5', "dob": '1910-01-01T05:00:00'  },
{ 'id': 6, 'name': 'sample6', "dob": '1901-10-09T05:00:00'  },
];

ngOnInit() {
    setTimeout(() => {
      this.loadStyles();
    }, 300);
  }

loadStyles() {
$(function () {
  $.fn.dataTable.moment('dd/MM/yyyy');

  $('#example').DataTable( {
    dom: 'Bfrtip',
    title: 'test',
    buttons: [
        'excel', 'pdf', 'print'
    ]
  });
});
}

}

This table is able to display the table and sort all the columns except the dob column. I've followed by their documentation but it gave me the same result. The date of birth or any other date field is not successfully sorted. Please assume that the dob is coming from the server as datetime format and I have all the necessary js codes. Any help would be appreciated!

Upvotes: 1

Views: 854

Answers (1)

davidkonrad
davidkonrad

Reputation: 85548

You are taken this a little bit the wrong direction:

  1. In DataTables, you only need to take special care of dates if they are not parseable, i.e if Date.parse() return NaN you'll need a plugin / formatter.

  2. DataTables momentjs sorting plugin is such a formatter. It is used to convert data into the right parseable format, not to show or display data.

  3. Your dates are perfectly fine, moment.js not needed. The native sorting breaks if any of the dates are illegal, for example null. To overcome this, you can force the type by

    columns: [
      { data: 'dob', type: 'date' }
    ]
  1. I believe you actually want to show the dates formatted as DD/MM/YYYY (dd/MM/yyyy return something like Mo/01/yyyy); you can use a render callback to show formatted dates while maintaining the native datetime sorting :
    columns: [
      { data: 'dob', 
        type: 'date',
        render: function(data, type) {
          return type == 'display' ? moment(data).format('DD/MM/YYYY') : data
        }
      } 
    ]

Upvotes: 1

Related Questions