如何在JavaScript中将时间戳转换为天数?求正确解决方案
修复时间戳天数差计算的问题
我来帮你排查这个时间差计算函数的问题,并且给出符合需求的正确方案~
原函数的核心问题
你的函数返回错误大概率是以下两个原因:
- 时间戳单位不统一:API返回的
endtimestamp通常是秒级Unix时间戳(比如10位数字),而Date.now()返回的是毫秒级(13位数字),直接相减会导致差值是实际值的1000倍,计算结果完全偏离预期。 - 未处理未来时间的情况:如果
endtimestamp是未来的时间,current - previous会得到负数,直接进入最小时间差的分支,返回秒数,显然不符合你要计算天数差的需求。
针对需求的解决方案
根据你要计算endtimestamp和当前时间天数差的需求,分两种场景给出修复后的代码:
场景1:按24小时为一天的粗略天数差
如果只需要计算两个时间戳之间间隔了多少个24小时(不考虑日历上的自然日边界),可以用这个函数:
function getDayDifference(currentTimestamp, targetTimestamp) { // 统一时间戳单位:如果目标是秒级,转成毫秒 const currentMs = typeof currentTimestamp === 'number' ? currentTimestamp : Date.now(); const targetMs = targetTimestamp.toString().length === 10 ? targetTimestamp * 1000 : targetTimestamp; const msPerDay = 24 * 60 * 60 * 1000; // 取绝对值避免正负问题,round四舍五入,也可以用floor取整 const dayDiff = Math.round(Math.abs(currentMs - targetMs) / msPerDay); return dayDiff; } // 使用示例:假设API返回的endtimestamp是秒级 const endTimestamp = 1717209600; // 对应2024-06-01 00:00:00 UTC const days = getDayDifference(Date.now(), endTimestamp); console.log(`天数差:${days}天`);
场景2:按自然日计算的精确天数差
如果需要按日历上的日期计算(比如今天23点到明天1点,就算1天),可以通过清除时分秒的方式来计算:
function getNaturalDayDifference(currentTimestamp, targetTimestamp) { // 统一时间戳单位 const currentMs = typeof currentTimestamp === 'number' ? currentTimestamp : Date.now(); const targetMs = targetTimestamp.toString().length === 10 ? targetTimestamp * 1000 : targetTimestamp; // 创建日期对象并清除时分秒,只保留日期部分 const currentDate = new Date(currentMs); currentDate.setHours(0, 0, 0, 0); const targetDate = new Date(targetMs); targetDate.setHours(0, 0, 0, 0); const msPerDay = 24 * 60 * 60 * 1000; // 计算两个日期的差值,取绝对值 const dayDiff = Math.abs((currentDate - targetDate) / msPerDay); return dayDiff; } // 使用示例 const endTimestamp = 1717209600; const days = getNaturalDayDifference(Date.now(), endTimestamp); console.log(`自然日天数差:${days}天`);
如果你想保留原函数的相对时间字符串功能
如果只是想修复原函数的错误,让它能正确返回诸如“X days ago”的字符串,可以这样修改:
function timeDifference(current, previous) { // 统一时间戳单位 const currentMs = typeof current === 'number' ? current : Date.now(); const previousMs = previous.toString().length === 10 ? previous * 1000 : previous; const msPerMinute = 60 * 1000; const msPerHour = msPerMinute * 60; const msPerDay = msPerHour * 24; const msPerMonth = msPerDay * 30; const msPerYear = msPerDay * 365; // 取绝对值,兼容过去和未来的时间 const elapsed = Math.abs(currentMs - previousMs); if (elapsed < msPerMinute) { return Math.round(elapsed/1000) + ' seconds ago'; } else if (elapsed < msPerHour) { return Math.round(elapsed/msPerMinute) + ' minutes ago'; } else if (elapsed < msPerDay ) { return Math.round(elapsed/msPerHour ) + ' hours ago'; } else if (elapsed < msPerMonth) { return Math.round(elapsed/msPerDay) + ' days ago'; } else if (elapsed < msPerYear) { return Math.round(elapsed/msPerMonth) + ' months ago'; } else { return Math.round(elapsed/msPerYear ) + ' years ago'; } }
内容的提问来源于stack exchange,提问作者Sachin Doifode




