You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Datatables框架中实现日期列按日期正确排序?

Fix Full Datetime Sorting Issue in 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:

  • mm refers to minutes, not months
  • MM is 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.js and the DataTables Moment sorting plugin before your initialization code—without these, the datetime-moment type won't work.
  • Column Index: Confirm targets: 6 points 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:32:37