Javascript 时间戳到相对时间 [英] Javascript timestamp to relative time

查看:45
本文介绍了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 时间戳到相对时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆