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

Node.js中如何从时间戳获取日期并在前端正常展示

前端时间戳转可读日期格式解决方案

你现有代码已经正确存储了毫秒级时间戳,不需要修改提交到服务端的逻辑,只需要补充时间格式化方法,在前端渲染帖子内容时调用即可。

可直接复用的格式化工具函数

/**
 * 毫秒时间戳转可读日期字符串
 * @param {number} timestamp 毫秒级时间戳
 * @param {string} format 输出格式,默认值为 YYYY-MM-DD HH:mm:ss
 * @returns {string} 格式化后的可展示日期
 */
const formatTimestamp = (timestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second);
}

代码调整步骤

  • 先检查现有代码中timestamps: date.getTime()里的date变量是否提前声明,如果没有就在对应位置补const date = new Date(),避免出现未定义报错。
  • 修改帖子渲染函数addPosteClient,不要直接插入原始时间戳,调用格式化方法处理后再渲染到页面:
const addPosteClient = (postData) => {
  // 处理时间为可读格式
  const displayTime = formatTimestamp(postData.timestamps);
  // 需要自定义展示格式时传入第二个参数即可,比如中文格式:
  // const displayTime = formatTimestamp(postData.timestamps, 'YYYY年MM月DD日 HH:mm');

  // 你原有的DOM渲染逻辑,将displayTime插入到页面对应的时间展示节点即可
  // 示例:postElement.querySelector('.post-time').textContent = displayTime;
}

常见问题排查

  • 如果格式化后日期显示为1970年,先检查时间戳长度:getTime()生成的是13位毫秒时间戳,如果后端返回的是10位秒级时间戳,需要乘以1000之后再传入格式化函数。
  • 如果需要显示相对时间(比如「5分钟前」「昨天」),可以在上述格式化函数的基础上扩展时间差判断逻辑,不需要引入额外第三方依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 00:48:31