如何用JavaScript(jQuery)在HTML中显示3s ago类相对时间
评论实时相对时间显示实现方案
你当前用服务器端的{% now %}标签生成的是固定格式时间,没法实时转换成3s ago这类相对时间,得用前端逻辑处理,下面是几种可行方案:
一、自定义相对时间计算函数
自己写一个简单函数,根据当前时间和评论发布时间的差值生成对应相对时间文本:
// 计算相对时间的函数 function getRelativeTime(timestamp) { const now = Date.now(); const diffMs = now - timestamp; const seconds = Math.floor(diffMs / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24); if (seconds < 60) return `${seconds}s ago`; if (minutes < 60) return `${minutes}m ago`; if (hours < 24) return `${hours}h ago`; return `${days}d ago`; }
修改评论插入代码,先获取当前时间戳再生成相对时间:
// 获取评论发布时的时间戳(毫秒) const commentTime = Date.now(); // 生成相对时间文本 const relativeText = getRelativeTime(commentTime); // 拼接HTML内容(用模板字符串更简洁) let _html = ` <div class="details_Comment"> <h4><b>{{c.user.username|title}}</b> <span>${relativeText}</span></h4> <p>${_comment}</p> </div> `; $(".comment-wrapper").prepend(_html);
二、使用浏览器原生API(Intl.RelativeTimeFormat)
如果不需要兼容IE,可直接用浏览器原生提供的Intl.RelativeTimeFormat API,生成符合语言习惯的标准相对时间:
// 初始化相对时间格式化器(en-US对应英文格式,如"3s ago") const timeFormatter = new Intl.RelativeTimeFormat('en-US', { style: 'narrow' }); function getRelativeTime(timestamp) { const now = Date.now(); const diffMs = now - timestamp; const seconds = Math.floor(diffMs / 1000); if (seconds < 60) return timeFormatter.format(-seconds, 'second'); const minutes = Math.floor(seconds / 60); if (minutes < 60) return timeFormatter.format(-minutes, 'minute'); const hours = Math.floor(minutes / 60); if (hours < 24) return timeFormatter.format(-hours, 'hour'); const days = Math.floor(hours / 24); return timeFormatter.format(-days, 'day'); }
调用方式和自定义函数一致,若要切换成中文格式,只需把en-US改成zh-CN,会自动生成"3秒前"这类文本。
三、实现动态更新相对时间
如果希望评论时间能随时间推移自动更新(比如从59s ago变成1m ago),可以给时间元素加上时间戳属性,再定时批量更新:
- 修改HTML拼接代码,给时间span添加
data-timestamp属性:
let _html = ` <div class="details_Comment"> <h4><b>{{c.user.username|title}}</b> <span class="comment-time" data-timestamp="${commentTime}">${relativeText}</span></h4> <p>${_comment}</p> </div> `;
- 编写批量更新函数,用定时器定期执行:
function updateAllCommentTimes() { $(".comment-time").each(function() { const timestamp = parseInt($(this).data('timestamp')); $(this).text(getRelativeTime(timestamp)); }); } // 每隔30秒更新一次所有评论的时间 setInterval(updateAllCommentTimes, 30000);
内容的提问来源于stack exchange,提问作者Destiny Franks
相关产品推荐
相关产品推荐

