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

React MUI DataGrid中Firestore时间戳转日期报Invalid Date

报错根因

你的时间取值路径写错了:

  • MUI DataGrid 的valueFormatter回调里,当前单元格的原始值存在params.value属性下,Firestore Timestamp的seconds、nanoseconds字段是嵌套在params.value里的,不是直接挂在params顶层。
  • 现有代码直接读params.seconds、params.nanoseconds拿到的都是undefined,计算出的时间戳是NaN,传入Date构造函数必然返回Invalid Date。
  • 你配置了type: "date"时MUI会自带默认日期格式化逻辑,自定义输出格式时建议去掉这个配置,避免格式冲突。
修正方案

修正取值路径,同时实现你要的dd, mm, yy格式输出,代码如下:

{
  field: "createdAt",
  headerName: "Tarih",
  width: 240,
  valueFormatter: (params) => {
    if (!params.value) return "";

    // 正确从params.value下取Firestore时间戳字段
    const fireBaseTime = new Date(
      params.value.seconds * 1000 + params.value.nanoseconds / 1000000
    );

    // 格式化为dd, mm, yy
    const day = String(fireBaseTime.getDate()).padStart(2, '0');
    // 注意JS月份从0开始计数,必须+1
    const month = String(fireBaseTime.getMonth() + 1).padStart(2, '0');
    const year = String(fireBaseTime.getFullYear()).slice(-2);

    return `${day}, ${month}, ${year}`;
  },
}

简便写法:如果你的项目里Firestore Timestamp没有做序列化转普通对象,本身是Timestamp类实例的话,可以直接调用内置方法转Date,不用手动算毫秒:

const fireBaseTime = params.value.toDate();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:24:30