计算两个日期差值时出现异常,输出1970年日期问题求助
问题原因分析
你看到的Thu Jan 01 1970 ...是Unix纪元起始时间(1970-01-01T00:00:00Z)的本地时区转换结果,出现这个情况的核心原因是你传入Date构造函数的数值不符合预期:
1. 第一种代码的问题
const expiryTimestamp = new Date((+expires - +now) / (1000 * 60 * 60 * 24))
+expires - +now得到的是两个日期的毫秒级时间差(如果expires早于当前时间,结果为负数)- 你把这个差值除以
1000*60*60*24,得到的是天数差(比如过期100天就是-100左右) - 但
Date构造函数接受的参数是从纪元开始的毫秒数,不是天数。把一个很小的负数(比如-100)传给它,相当于从纪元时间往前推100毫秒,结果自然是纪元附近的日期。
2. 第二种代码的问题
const expiryTimestamp = new Date((+expires - +now))
如果输出还是1970年的日期,大概率是flash?.expires的解析出了问题:
- 如果
flash?.expires是undefined或者无效的日期格式,new Date(undefined)会返回Invalid Date,+Invalid Date的结果是NaN NaN - +now还是NaN,new Date(NaN)在部分JS环境中会显示为纪元起始时间的本地时区版本。
解决方法
你的需求是计算两个日期的差值,不需要把差值再传给Date构造函数,直接计算出天数/小时/分钟差即可:
方案1:计算剩余天数(区分已过期/未过期)
const expires = new Date("2022-09-15T17:00:00.000+00:00"); const now = new Date(); // 计算毫秒差,转换成天数(取整或保留小数) const diffMs = +expires - +now; const diffDays = diffMs / (1000 * 60 * 60 * 24); if (diffDays > 0) { console.log(`还有${Math.floor(diffDays)}天到期`); } else { console.log(`已过期${Math.floor(-diffDays)}天`); }
方案2:确保日期解析正确(针对后端返回的字段)
如果使用后端返回的flash?.expires,先验证日期是否有效:
const expiresStr = flash?.expires; if (!expiresStr) { console.log("未获取到有效到期日期"); return; } const expires = new Date(expiresStr); if (isNaN(+expires)) { console.log("日期格式无效,无法解析"); return; } const now = new Date(); const diffMs = +expires - +now; const diffDays = diffMs / (1000 * 60 * 60 * 24); console.log(`日期差值:${diffDays.toFixed(2)}天`);
内容的提问来源于stack exchange,提问作者Md Ali
相关产品推荐
相关产品推荐

