Javascript时间戳到相对时间(例如2秒前,一个星期前等),最好的方法? [英] Javascript timestamp to relative time (eg 2 seconds ago, one week ago etc), best methods?

查看:796
本文介绍了Javascript时间戳到相对时间(例如2秒前,一个星期前等),最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个很好的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天而不是 1天)如果这麻烦你。

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时间戳到相对时间(例如2秒前,一个星期前等),最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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