如何在Datatables框架中实现日期列按日期正确排序?
Looks like the core issue here is a format string mistake in your moment.js configuration, plus a small syntax error in your DataTables initialization. Let's break down how to fix this:
Step 1: Correct the Moment Format String
Your date format is ddd.mm.YYYY HH:mm, but in moment.js:
mmrefers to minutes, not monthsMMis the correct token for two-digit months
This is why your sorting only works by day—your code was parsing the month value as minutes, so DataTables couldn't recognize the actual month/year for proper sorting. Update the format to:
$.fn.dataTable.moment('ddd.MM.YYYY HH:mm');
Step 2: Fix the DataTables Initialization Syntax
Your original code has a closing bracket error ()} instead of });). Here's the corrected, full initialization code (wrapped in document.ready to ensure the DOM is loaded first):
$(document).ready(function() { // Register the correct datetime format first $.fn.dataTable.moment('ddd.MM.YYYY HH:mm'); // Initialize the DataTable $('#requests_table').DataTable({ columnDefs: [ { type: 'datetime-moment', targets: 6 // Double-check this is the correct index for your Creation Date column (starts at 0) } ] }); });
Key Notes to Verify
- Dependencies: Make sure you've loaded both
moment.jsand the DataTables Moment sorting plugin before your initialization code—without these, thedatetime-momenttype won't work. - Column Index: Confirm
targets: 6points to the correct column (DataTables uses 0-based indexing, so this is the 7th column in your table). If your Creation Date column is in a different position, adjust this number accordingly.
That should fix the sorting so it orders by the full datetime (year → month → day → hour → minute) instead of just the day value.
内容的提问来源于stack exchange,提问作者Mohamed Ali O.Ameur

