React中如何正确转换并显示后端返回的时间戳为日期时间?
解决React中时间戳转日期显示「Invalid Date」的问题
嘿,我帮你排查下这个「Invalid Date」的问题~ 出现这个情况大概率是时间戳的类型不对,或者你没注意到后端返回的是秒级时间戳而非毫秒级,下面给你一步步解决的方案:
1. 先确认时间戳的类型
后端返回的createdAt如果是字符串格式的数字(比如 "1635424532797"),直接传给new Date()会出错——因为new Date()接收字符串时,会把它当作日期字符串解析(比如"2021-10-28"),而不是时间戳。这时候需要先把它转成数字类型:
// 正确写法:先转数字再传入Date const timestamp = "1635424532797"; // 后端返回的字符串类型时间戳 const date = new Date(Number(timestamp)); console.log(date.toLocaleDateString("en-US")); // 输出 "10/28/2021"
你也可以用parseInt来转换,效果一样:
new Date(parseInt(timestamp, 10)).toLocaleDateString("en-US")
2. 处理空值/无效值的边界情况
避免因为后端返回null、undefined或者非数字导致的报错,可以写一个通用的格式化函数:
const formatCreatedAt = (timestamp) => { // 先判断时间戳是否有效 if (!timestamp || isNaN(Number(timestamp))) { return "N/A"; // 或者返回你想要的默认提示 } const date = new Date(Number(timestamp)); return date.toLocaleDateString("en-US"); };
3. 额外检查:时间戳是秒级还是毫秒级?
如果上面的方法还是不行,要确认后端返回的是毫秒级时间戳还是秒级时间戳:
- JS的
new Date()默认需要毫秒级(13位数字,比如1635424532797) - 如果后端返回的是秒级(10位数字,比如1635424532),需要乘以1000再传入:
const secondTimestamp = 1635424532; // 秒级时间戳 const date = new Date(secondTimestamp * 1000); console.log(date.toLocaleDateString("en-US")); // 同样输出 "10/28/2021"
4. 显示完整的日期时间(可选)
如果需要同时显示日期和时间,用toLocaleString()代替toLocaleDateString(),还可以自定义格式:
date.toLocaleString("en-US", { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }); // 输出 "October 28, 2021, 09:15:32 AM"
React组件示例
把上面的逻辑放到React组件里,大概是这样:
import React from 'react'; const PostCard = ({ post }) => { const formatCreatedAt = (timestamp) => { if (!timestamp || isNaN(Number(timestamp))) { return "Invalid Date"; } // 假设后端返回的是字符串类型的毫秒级时间戳 const date = new Date(Number(timestamp)); return date.toLocaleString("en-US", { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }); }; return ( <div className="post-card"> <h3>{post.title}</h3> <p>Created at: {formatCreatedAt(post.createdAt)}</p> </div> ); }; export default PostCard;
内容的提问来源于stack exchange,提问作者Shruthi R
相关产品推荐
相关产品推荐

