Quick Tip on Using the DataTables Ultimate Date/Time Sorting Plugin


If the date/time column data does not sort correctly using DataTables, then you need to use the ultimate date/time sorting plugin. Here are the steps:

  • Include the moment.js JavaScript library
  • Include the DataTables date/time sorting plugin
  • Define the date/time format to detect

In the page head section, add the following code snippet:


<!doctype html>
<html>
<head>
  <title>DataTables Date/Time Sorting Plugin</title>
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
  <script src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
</head>
<body>

  //code snippet to define and sort date/time columns goes here

</body>
</html>

Register the date/time format to detect and order using the $.fn.dataTable.moment( format, locale ) method, which accepts up to two parameters:

  • format – The date / time format to detect and order, and is required.
  • locale (optional) – This option can be used to specify a locale.

For format and locale available for use, please refer to the following links below:

Here’s a code snippet example to illustrate:


<!doctype html>
<html>
<head>
  <title>DataTables Date/Time Sorting Plugin</title>
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
  <script src="//cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>
</head>
<body>

<script>
  $(document).ready(function() {
    $.fn.dataTable.moment( 'DD/MM/YYYY' );
    $.fn.dataTable.moment( 'dddd, DD/MM/YYYY' );
    $('#myexample').DataTable();
  } );
</script>

</body>
</html>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s