在JavaScript中将Unix时间转换为"分钟前"

Rus*_*wer 3 javascript php unix time date

我想隐瞒PHP创建并存储在我们数据库中的time()几分钟之前,当JSON请求我们的JavaScript捕获它时.

http://media.queerdio.com/mobileDevice/?uri=nowplaying/1

你可以看到我们存储的时间就像

"airtime":1382526339
Run Code Online (Sandbox Code Playgroud)

我们想把它变成什么

3 minutes ago
Run Code Online (Sandbox Code Playgroud)

这就是我们所知道的.

我们首先需要运行这样的东西

function convert_time(ts) {
   return new Date(ts * 1000) 
}
Run Code Online (Sandbox Code Playgroud)

采取通话时间并通过该功能运行它使得它与我读取的JavaScript兼容(我可能是错的)Unix时间javascript

那么我不知道如何从JavaScript日期时间到几分钟前.我们目前不使用jQuery,如果我们可以继续沿着这条路走下去会很棒,因为这是我完成编码之前的最后一个问题.

sit*_*sys 6

不需要任何依赖,只需普通的旧javascript就足够了.要将unix时间戳转换为"X time ago"类似标签,您只需使用以下内容:

function time2TimeAgo(ts) {
    // This function computes the delta between the
    // provided timestamp and the current time, then test
    // the delta for predefined ranges.

    var d=new Date();  // Gets the current time
    var nowTs = Math.floor(d.getTime()/1000); // getTime() returns milliseconds, and we need seconds, hence the Math.floor and division by 1000
    var seconds = nowTs-ts;

    // more that two days
    if (seconds > 2*24*3600) {
       return "a few days ago";
    }
    // a day
    if (seconds > 24*3600) {
       return "yesterday";
    }

    if (seconds > 3600) {
       return "a few hours ago";
    }
    if (seconds > 1800) {
       return "Half an hour ago";
    }
    if (seconds > 60) {
       return Math.floor(seconds/60) + " minutes ago";
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以根据需要更改文本/范围.

希望这会有所帮助,我的观点是你不需要使用任何库来实现这种事情:)


Sas*_*olf 5

我建议你Moment.js一个小的(8.8 kb 缩小)javascript 库,用于格式化日期对象。它工作得非常好,没有进一步的依赖。