将 Twitter created_at 显示为 xxxx 前的 JavaScript 代码 [英] JavaScript code to display Twitter created_at as xxxx ago

查看:32
本文介绍了将 Twitter created_at 显示为 xxxx 前的 JavaScript 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些 JS 代码来从 Twitter 提要中获取 created_at 值并将其显示为 xxxx ago.

I need some JS code that will take the created_at value from a Twitter feed and display it as xxxx ago.

我可以找到创建 xxxx ago 位的示例,但找不到将 created_at 位转换为 JS 正确格式的示例.

I can find examples of creating the xxxx ago bit but not examples of getting the created_at bit into the correct format for JS.

有没有人有一个多合一的功能来做我想做的事?

Does anyone have an all in one function to do what I'm after?

示例格式 Tue Apr 07 22:52:51 +0000 2009

不能使用 new Date(Date.parse("Tue Apr 07 22:52:51 +0000 2009")) 因为它在 IE 中给出了无效的日期错误.

Cannot use new Date(Date.parse("Tue Apr 07 22:52:51 +0000 2009")) as it gives an invalid date error in IE.

推荐答案

来自评论和 Twitter 小部件的一些代码是我想出的代码:

From the comments, and some code from the twitter widget here is the code I came up with:

function parseTwitterDate(tdate) {
    var system_date = new Date(Date.parse(tdate));
    var user_date = new Date();
    if (K.ie) {
        system_date = Date.parse(tdate.replace(/( +)/, ' UTC$1'))
    }
    var diff = Math.floor((user_date - system_date) / 1000);
    if (diff <= 1) {return "just now";}
    if (diff < 20) {return diff + " seconds ago";}
    if (diff < 40) {return "half a minute ago";}
    if (diff < 60) {return "less than a minute ago";}
    if (diff <= 90) {return "one minute ago";}
    if (diff <= 3540) {return Math.round(diff / 60) + " minutes ago";}
    if (diff <= 5400) {return "1 hour ago";}
    if (diff <= 86400) {return Math.round(diff / 3600) + " hours ago";}
    if (diff <= 129600) {return "1 day ago";}
    if (diff < 604800) {return Math.round(diff / 86400) + " days ago";}
    if (diff <= 777600) {return "1 week ago";}
    return "on " + system_date;
}

// from http://widgets.twimg.com/j/1/widget.js
var K = function () {
    var a = navigator.userAgent;
    return {
        ie: a.match(/MSIEs([^;]*)/)
    }
}();

这篇关于将 Twitter created_at 显示为 xxxx 前的 JavaScript 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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