如何让Moment.js始终以小时为单位输出相对时间字符串?
如何让Moment.js始终以小时为单位输出相对时间?
你的代码中,Moment.js的from()方法会自动根据时间差切换单位(比如24小时自动转为"day"),要实现始终以小时为单位输出,直接用diff()方法计算两个时间的小时差即可,无需依赖from()的自动转换逻辑。
解决方案代码示例
// 基础实现 let hours = 5; const pastTime = moment().subtract(hours, 'hours'); const hourDifference = moment().diff(pastTime, 'hours'); console.log(`${hourDifference} ${hourDifference === 1 ? 'hour' : 'hours'}`); // 输出 "5 hours" hours = 24; const pastTime2 = moment().subtract(hours, 'hours'); const hourDifference2 = moment().diff(pastTime2, 'hours'); console.log(`${hourDifference2} ${hourDifference2 === 1 ? 'hour' : 'hours'}`); // 输出 "24 hours"
如果需要复用,可以封装成函数:
function getRelativeHourString(targetTime) { const hourDiff = moment().diff(targetTime, 'hours'); return `${hourDiff} ${hourDiff === 1 ? 'hour' : 'hours'}`; } // 使用示例 console.log(getRelativeHourString(moment().subtract(1, 'hours'))); // "1 hour" console.log(getRelativeHourString(moment().subtract(48, 'hours'))); // "48 hours"
原理说明
Moment.js的from()方法内置了单位优先级换算规则,当时间差达到对应单位阈值时会自动切换展示单位。而diff(target, 'hours')方法可以直接获取两个时间之间精确的小时差值,再手动处理单复数后缀,就能实现始终以小时为单位输出的需求。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

