Datatables

Change Date Format in DataTables

1 min read

In this tutorial, we will discuss how to change the date format in a table created with DataTables.
We will use JavaScript and jQuery to achieve this.

Preparation

Make sure you have DataTables ready to use.
If not, you can visit the official DataTables website for a guide on how to install it.

Start Code

Here is the initial code we have:

$(document).ready(function(){
  $('#mytable').DataTable({
    responsive: true,
    dom: 'Blfrtip',
    buttons: [
      'excel', 'pdf', 'copy', 'print'
    ],
    lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ],
    pageLength: 10,
    columnDefs: [
      { 
        targets: [5, 6], // Mengubah indeks kolom menjadi 5 dan 6 (kolom 6 dan 7 dalam basis 0)
        render: function(data) {
          if(data) {
            var dateSplit = data.split('-');
            return dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[0];
          }
          return data;
        }
      }
    ]
  });
});

This code should change the date format in columns 6 and 7 from ‘yyyy-mm-dd’ to ‘dd-mm-yyyy’.
However, only column 7 changes its format.

Solution

To fix this problem, we need to define the render function for each column separately.
Here is the corrected code:

$(document).ready(function(){
  $('#mytable').DataTable({
    responsive: true,
    dom: 'Blfrtip',
    buttons: [
      'excel', 'pdf', 'copy', 'print'
    ],
    lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ],
    pageLength: 10,
    columnDefs: [
      { 
        targets: [5], // Mengubah indeks kolom menjadi 5 (kolom 6 dalam basis 0)
        render: function(data) {
          if(data) {
            var dateSplit = data.split('-');
            return dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[0];
          }
          return data;
        }
      },
      { 
        targets: [6], // Mengubah indeks kolom menjadi 6 (kolom 7 dalam basis 0)
        render: function(data) {
          if(data) {
            var dateSplit = data.split('-');
            return dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[0];
          }
          return data;
        }
      }
    ]
  });
});

In this way, each column has its own render function and both are processed correctly.

Conclusion

In this tutorial, we have learned how to change the date format in DataTables using JavaScript and jQuery. Good luck!


Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Chat!
1