You need to enable JavaScript to run this app. 如何在导出Excel/CSV前插入代码格式化API返回的时间字段?
优惠活动
大模型
产品
解决方案
定价
更多

如何在导出Excel/CSV前插入代码格式化API返回的时间字段?

实现方案

直接插入代码的方法

你不需要改动现有逻辑结构,只需要在DataSet的data字段遍历逻辑中,对latest_time_of_visit做转换即可。如果你的预期是仅保留YYYY-MM-DD格式的日期,修改后的代码如下:

const DataSet = [
  {
    columns: [
      {
        title: "S/N",
        style: { font: { sz: "18", bold: true } },
        width: { wpx: 100 },
      },
      {
        title: "Customer Information",
        style: { font: { sz: "18", bold: true } },
        width: { wpx: 250 },
      },
      {
        title: "Customer Email",
        style: { font: { sz: "18", bold: true } },
        width: { wpx: 250 },
      },
      {
        title: "Counts of Visit",
        style: { font: { sz: "18", bold: true } },
        width: { wpx: 175 },
      },
      {
        title: "Latest Time of Visit",
        style: { font: { sz: "18", bold: true } },
        width: { wpx: 250 },
      },
      {
        title: "Contacted?",
        style: { font: { sz: "18", bold: true } },
        width: { wpx: 250 },
      },
    ],
    data: customerList.map((val) => {
      // 新增日期转换逻辑,增加边界判断避免无效日期报错
      let formattedVisitTime = ''
      if (val.latest_time_of_visit) {
        const date = new Date(val.latest_time_of_visit)
        if (!isNaN(date.getTime())) {
          // 仅需要日期就保留这行
          formattedVisitTime = date.toLocaleDateString("en-CA")
          // 如果需要保留日期+时间,替换为下面两行即可
          // const timeStr = date.toLocaleTimeString()
          // formattedVisitTime = `${formattedVisitTime} ${timeStr}`
        } else {
          formattedVisitTime = val.latest_time_of_visit
        }
      }
      return [
        { value: val.ID, style: { font: { sz: "14" } } },
        { value: val.name, style: { font: { sz: "14" } } },
        { value: val.email, style: { font: { sz: "14" } } },
        { value: val.counts_of_visit, style: { font: { sz: "14" } } },
        // 替换为转换后的日期值
        { value: formattedVisitTime, style: { font: { sz: "14" } } },
        { value: val.contacted, style: { font: { sz: "14" } } },
      ]
    }),
  },
];

更优的日期格式化方案

  • 后端SQL查询直接格式化:如果API数据来自SQL数据库,直接在查询语句中完成日期格式化,前端无需额外处理,性能最优。比如MySQL使用DATE_FORMAT(latest_time_of_visit, '%Y-%m-%d'),PostgreSQL使用to_char(latest_time_of_visit, 'YYYY-MM-DD')。
  • 使用轻量日期库统一处理:如果前端需要频繁处理不同格式的日期,推荐使用dayjs这类体积仅2KB的轻量库,兼容性远优于原生Date对象,格式化代码更简洁易维护,示例:dayjs(val.latest_time_of_visit).format('YYYY-MM-DD'),还可直接处理时区、相对时间等复杂需求。
  • 封装公用工具函数:如果不想引入第三方依赖,把日期转换逻辑封装为全局公用函数,所有需要转日期的场景统一调用,避免重复代码,也方便后续统一修改日期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 07:06:05