简体   繁体   中英

Datatables datetime format sorting problem

I want to format the Date column. (DD.MM.YYYY HH:mm ) I also get an error in the order. Sorting does not work in this format.

在此处输入图片说明

1.) Do you have the moment script linked to your HTML?

IF not be sure to add the following in the <head> tag of your html <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>

IF so. You can do the following.

Instead of rendering it in columnDefs, you can actually reformat the date in the column initialization like so:

 moment.suppressDeprecationWarnings = true; var dataSet = [ { "Something" : "Something1", "Date" : "01/12/2021" } ] $(document).ready(function() { $('#example').DataTable( { data: dataSet, columns: [ { "data": "Something" }, { "data": "Date", render: function(data, type, row) { //render function to format the date values from my AJAX if (type === "sort" || type === "type") { return data; } return moment(data).format("DD.MM.YYYY HH:mm"); } } ] } ); } );
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--stylesheets--> <!-- <link rel="stylesheet" href="site.css"> --> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.css"/> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4-4.6.0/jq-3.3.1/dt-1.11.0/af-2.3.7/date-1.1.1/r-2.2.9/rg-1.1.3/datatables.css"/> <!--scripts--> <!-- <script src="main.js"></script> --> <script type="text/javascript" src="https://cdn.datatables.net/v/bs4-4.6.0/jq-3.3.1/dt-1.11.0/af-2.3.7/date-1.1.1/r-2.2.9/rg-1.1.3/datatables.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script> </head> <body> <div class="container"> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead class="thead-light"> <tr> <th>Something</th> <th>Date</th> </tr> </thead> </table> </div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM