Javascript 时间戳到相对时间

编程入门 行业动态 更新时间:2024-10-25 04:17:38
本文介绍了Javascript 时间戳到相对时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一个不错的 JS 代码段来将时间戳(例如来自 Twitter API)转换为一个很好的用户友好的相对时间(例如 2 秒前、一周前等).

I'm looking for a nice JS snippet to convert a timestamp (e.g. from Twitter API) to a nice user friendly relative time (e.g. 2 seconds ago, one week ago etc).

有人愿意分享一些他们最喜欢的方法吗(最好不要使用插件)?

Anyone care to share some of their favourite methods (preferably not using plugins)?

推荐答案

如果您不太关心准确性,这很容易.微不足道的方法有什么问题?

Well it's pretty easy if you aren't overly concerned with accuracy. What wrong with the trivial method?

function timeDifference(current, previous) { var msPerMinute = 60 * 1000; var msPerHour = msPerMinute * 60; var msPerDay = msPerHour * 24; var msPerMonth = msPerDay * 30; var msPerYear = msPerDay * 365; var elapsed = current - previous; 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 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago'; } else if (elapsed < msPerYear) { return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago'; } else { return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago'; } }

工作示例这里.

如果这让您感到困扰,您可能想要调整它以更好地处理奇异值(例如 1 day 而不是 1 days).

You might want to tweak it to handle the singular values better (e.g. 1 day instead of 1 days) if that bothers you.

更多推荐

Javascript 时间戳到相对时间

本文发布于:2023-10-24 09:43:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523606.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!