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

如何在Material React Table(MRT)中正确排序日期字段?

修复Material React Table中DD-MM-YYYY格式日期的排序问题

问题背景

在React项目中使用Material React Table(MRT)时,遇到一个日期字段格式为31-08-2023 09:52:55,排序时仅按字符串前几位比较,无法正确按日期(年、月、时间)排序。尝试自定义排序函数后仍未解决。

问题原因

你自定义排序函数中,用new Date(getLocalDateTime(...))解析日期时出错了——getLocalDateTime返回的还是DD-MM-YYYY HH:mm:ss格式的字符串,而JavaScript原生Date对象无法正确识别这种格式(它默认把DD-MM当成MM-DD,比如31-08会被解析成无效日期),导致排序逻辑失效。

解决方案

方法1:用Moment正确解析原始日期做排序

直接基于原始日期字符串,用moment解析成日期对象后比较时间戳,不要用getLocalDateTime返回的格式化字符串:

sortingFn: (rowA, rowB) => {
  // 用moment解析原始的DD-MM-YYYY格式日期
  const dateA = moment(rowA.original.lastModifiedDate, DATE_FORMATS.D_M_Y_TIME).valueOf();
  const dateB = moment(rowB.original.lastModifiedDate, DATE_FORMATS.D_M_Y_TIME).valueOf();
  
  return dateA - dateB;
}

方法2:用accessorFn返回可排序的日期值

如果想复用MRT自带的datetime排序函数,可以通过accessorFn返回日期对象或者时间戳,而不是原始的字符串:

const columns = useMemo<MRT_ColumnDef<User>[]>(
  () => [
    {
      accessorKey: 'lastModifiedDate',
      header: 'Last Updated',
      Cell: ({ row }) => processLastModifiedDate(row),
      // 用accessorFn返回日期对象,让MRT的datetime排序生效
      accessorFn: (row) => moment(row.lastModifiedDate, DATE_FORMATS.D_M_Y_TIME).toDate(),
      sortingFn: 'datetime',
    },
  ],
  [],
);

额外提示

如果你的原始日期是UTC格式,记得在解析时保持UTC处理,避免时区影响排序结果:

// 解析UTC日期的示例
accessorFn: (row) => moment.utc(row.lastModifiedDate, DATE_FORMATS.D_M_Y_TIME).toDate(),

内容的提问来源于stack exchange,提问作者David Johns

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:35:03