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

如何在JSpreadSheet中将13位Unix时间戳显示为日期格式?

JSpreadSheet-ce 实现13位毫秒级时间戳转标准日期显示(列配置方案)

问题根源

JSpreadSheet的DATE/CALENDAR类型默认解析10位秒级Unix时间戳,你的数据是13位毫秒级,直接用默认类型会导致解析失效,只能显示原始数字。

列配置实现方案(无需forEach遍历)

通过列的renderer(渲染)和editor(编辑)函数,在显示/编辑时自动处理毫秒戳与日期格式的转换,同时保留原始13位时间戳的数据存储。

完整可编辑列配置示例

jspreadsheet(document.getElementById('spreadsheet'), {
    worksheets: [{
        data: [
            [1696147200000], // 对应2023/10/01
            [1698825600000]  // 对应2023/11/01
        ],
        columns: [
            {
                type: 'date',
                title: '日期',
                dateFormat: 'YYYY/MM/DD',
                // 渲染时将13位毫秒戳转成标准日期格式
                renderer: function(value) {
                    if (value && typeof value === 'number' && value.toString().length === 13) {
                        // 用JSpreadSheet内置工具格式化日期
                        return jspreadsheet.helpers.dateFormat(new Date(value), 'YYYY/MM/DD');
                    }
                    return value;
                },
                // 编辑时适配日期编辑器,保存时转回毫秒戳
                editor: function(cell, value, x, y, instance) {
                    // 把毫秒戳转成秒级给日期编辑器使用
                    const initialValue = value?.toString().length === 13 ? Math.floor(value / 1000) : value;
                    const dateEditor = jspreadsheet.editors.date(cell, initialValue, x, y, instance);
                    
                    // 关闭编辑器时,将选中的日期转回13位毫秒戳存回单元格
                    dateEditor.onclose = function() {
                        const selectedDate = this.getValue();
                        if (selectedDate) {
                            instance.setValueFromCoords(x, y, new Date(selectedDate).getTime());
                        }
                    };
                    return dateEditor;
                }
            }
        ]
    }]
});

仅显示无需编辑的简化配置

如果不需要编辑功能,直接用text类型配合renderer即可:

columns: [
    {
        type: 'text',
        title: '日期',
        renderer: function(value) {
            if (value && typeof value === 'number' && value.toString().length === 13) {
                // 两种格式化方式二选一
                // 方式1:用JSpreadSheet内置工具
                return jspreadsheet.helpers.dateFormat(new Date(value), 'YYYY/MM/DD');
                // 方式2:用原生JS格式化
                // return new Date(value).toLocaleDateString('zh-CN', {
                //     year: 'numeric',
                //     month: '2-digit',
                //     day: '2-digit'
                // }).replace(/\//g, '/');
            }
            return value;
        }
    }
]

说明

  • 以上配置完全通过列参数实现转换,无需提前用forEach遍历处理原始数据。
  • 核心逻辑是利用renderer拦截显示过程,将毫秒戳转成格式化后的日期字符串;编辑场景则通过editor适配日期编辑器的输入输出,保证数据存储仍为13位时间戳。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:17:11