数据表和时刻

问题描述 投票:0回答:1

我正在使用数据表并在日期时间列上添加排序。 当日期时间格式为这样的日期 01/01/2021 10:11:20 AM 排序有效,但是当它的格式为这样 01/01/2021 10:11:20AM 它没有

我正在大量使用 moment.js

jquery datatables momentjs
1个回答
0
投票

您可以使用parseZone函数解析日期和时间字符串,并将它们转换为可以被DataTable正确排序的Moment.js对象。

这里有一个示例代码片段,演示了如何使用 Moment.js 和 DataTables 对日期和时间值进行排序:

// Assume that you have a DataTable object and a column named 'DateTime' that contains date and time strings formatted like '01/01/2021 10:11:20 AM' or '01/01/2021 10:11:20AM'

// Define a custom sorting function that uses Moment.js to parse the date and time strings and compare the resulting Moment.js objects
$.fn.dataTable.ext.type.order['moment-date-pre'] = function (dateString) {
  // Use Moment.js to parse the date and time string and convert it into a Moment.js object
  var momentObj = moment(dateString, ['MM/DD/YYYY h:mm:ss A', 'MM/DD/YYYY h:mm:ssA'], true).parseZone();
  
  // Return the Unix timestamp of the Moment.js object, which can be used by DataTables to sort the values
  return momentObj.unix();
};

// Use the 'moment-date-pre' sorting function to sort the 'DateTime' column in ascending order
$('#example').DataTable({
  columnDefs: [
    { type: 'moment-date', targets: [0] }
  ]
});

在这个例子中,我们使用 $.fn.dataTable.ext.type.order 为 Moment.js 定义了一个自定义排序函数。该函数使用 Moment.js 解析日期和时间字符串并将其转换为 Moment.js 对象,然后返回该对象的 Unix 时间戳。

然后我们使用 DataTable 的 columnDefs 选项将 moment-date-pre 排序功能应用于 DateTime 列。

注意,您可能需要调整 columnDefs 对象中的 Moment.js 格式字符串和 targets 选项,以匹配您自己的 DataTable 的结构和排序逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.