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

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

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