以下是我的一条推文对象的示例:
date: "2016-01-12T10:13:50Z"
formatted_date: "January 12, 2016 - 10:13 AM"
formatted_date_difference: "-20798 sec ago"
id: "68358314540"
link: true
literal_text: "One more mention of this: graphic novel night with DEATH theme. About 20 tickets remain. Come!... https://t.co/jInCQ2c8hv"
start_epoch: 1452615230
text: "One more mention of this: graphic novel night with DEATH theme. About 20 tickets remain. Come!... https://t.co/jInCQ2c8hv"
user_name: "watsoncomedian"
我正在尝试使用此formatted_date_difference: "-20798 sec ago"
到目前为止,我从this question找到了这个功能。
function beautifyTime(timeAgo) {
var seconds = Math.floor((new Date() - timeAgo) / 1000),
intervals = [
Math.floor(seconds / 31536000),
Math.floor(seconds / 2592000),
Math.floor(seconds / 86400),
Math.floor(seconds / 3600),
Math.floor(seconds / 60)
],
times = [
'year',
'month',
'day',
'hour',
'minute'
];
var key;
for(key in intervals) {
if (intervals[key] > 1)
return intervals[key] + ' ' + times[key] + 's ago';
else if (intervals[key] === 1)
return intervals[key] + ' ' + times[key] + ' ago';
}
return Math.floor(seconds) + ' seconds ago';
}
但是,当我输入beautifyTime(16275);
或beautifyTime(20798)
进行测试时,它总会在49年前返回。
答案 0 :(得分:0)
尝试这个,它是为它做的:moment
答案 1 :(得分:0)
以下是我根据答案创建的Angular服务:JavaScript code to display Twitter created_at as xxxx ago
(function() {
angular
.module('tweetDateFactory', [])
.factory('TweetDateFactory', factory);
factory.$inject = [];
function factory() {
/** Init TweetDateFactory scope */
/** ----------------------------------------------------------------- */
var tweetDateFactory = {
parseTwitterDate : parseTwitterDate
}
return tweetDateFactory;
////////////////////////////////////////////////////////////////////////
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(/MSIE\s([^;]*)/)
}
}();
}
})();