使用 Date 对象解析时间戳,再通过 Intl.DateTimeFormat 或手动拼接生成格式化字符串。
封装一个通用的JS时间戳转日期字符串函数
时间:2026-11-30
浏览:166
文章目录
时间戳解析与格式映射
前端接收到的通常是毫秒级时间戳(13位)或秒级时间戳(10位)。核心步骤是先统一转换为毫秒,再实例化 Date 对象。推荐使用 Intl.DateTimeFormat 处理本地化显示,它比正则替换更稳健且性能更好。
Intl.DateTimeFormat 接受语言标签和选项对象。通过设置 year, month, day 等属性,可以精确控制输出格式。例如 { year: 'numeric', month: '2-digit', day: '2-digit' } 会输出类似 2023/10/05 的字符串。这种方法自动处理了闰年、月份天数差异以及时区问题(默认使用浏览器所在时区,如需 UTC 可传入 timeZone: 'UTC')。
通用转换函数实现
将上述逻辑封装为工具函数,支持自定义分隔符和时区。代码应放在 utils/time.js 文件中,直接导入使用。
function formatTimestamp(timestamp, separator = '-', timeZone = null) {
if (!timestamp && timestamp !== 0) return '';
// 统一转换为毫秒
const ms = typeof timestamp === 'number'
? (timestamp.toString().length <= 10 ? timestamp * 1000 : timestamp)
: new Date(timestamp).getTime();
if (isNaN(ms)) return '';
const date = new Date(ms);
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
if (timeZone) {
options.timeZone = timeZone;
}
const formatter = new Intl.DateTimeFormat('zh-CN', options);
const parts = formatter.formatToParts(date);
// 提取各部分并组装
const getPart = (type) => parts.find(p => p.type === type)?.value || '';
const y = getPart('year');
const m = getPart('month');
const d = getPart('day');
const h = getPart('hour');
const min = getPart('minute');
const s = getPart('second');
return `${y}${separator}${m}${separator}${d} ${h}:${min}:${s}`;
}
// 测试用例
console.log(formatTimestamp(1696483200000)); // 2023/10/05 08:00:00 (假设本地时区)
console.log(formatTimestamp(1696483200, '/', 'UTC')); // 2023/10/05 00:00:00
运行上述代码,控制台将输出格式化后的日期字符串。第一个调用使用默认毫秒戳和分隔符,第二个调用演示了秒级时间戳转换及 UTC 时区设置。若输入非法时间戳,函数返回空字符串,避免页面显示 NaN 或 Invalid Date。
函数需处理输入验证,确保时间戳有效。同时提供可选参数以覆盖默认格式。
时区与边界值处理
当时间戳对应无效日期(如 2月30日)或跨天时,Date 对象会自动进位或回退。若需严格校验,应在格式化前检查 isNaN(date.getTime())。UTC 与本地时间的切换是常见坑点,务必明确需求。
在服务器渲染或特定业务场景下,可能需要强制使用 UTC 时间。此时只需在 options 中指定 timeZone: 'UTC' 即可。对于极端边界情况,建议返回空字符串或默认值而非抛出异常,以保持 UI 稳定性。
实用工具推荐
绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
选择画质和输出格式,预览压缩前后的大小。