将unix时间戳转换为twitter / facebook样式
I'm trying to convert a unix time stamp to display like facebook and twitter. For example, when you see tweets or comments placed on twitter/facebook you see the date/time displayed like so:
'2 mins ago' or '2 days ago' or '2 weeks ago'
Does anyone one know of any function to get it working like this. I'm guessing it will be a custom one.
Any help is much appreciated
我正在尝试将unix时间戳转换为facebook和twitter。 例如,当您在Twitter / Facebook上看到推文或评论时,您会看到显示的日期/时间如下: p>
'2分钟前'或'2天前'或'2周 以前' p>
有没有人知道任何功能让它像这样工作。 我猜这将是一个自定义的。 p>
非常感谢任何帮助 p> div>
If you are using php you might want to try the following function which was posted by Matt Jones
// DISPLAYS COMMENT POST TIME AS "1 year, 1 week ago" or "5 minutes, 7 seconds ago", etc...
function time_ago($date,$granularity=2) {
$date = strtotime($date);
$difference = time() - $date;
$periods = array('decade' => 315360000,
'year' => 31536000,
'month' => 2628000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
foreach ($periods as $key => $value) {
if ($difference >= $value) {
$time = floor($difference/$value);
$difference %= $value;
$retval .= ($retval ? ' ' : '').$time.' ';
$retval .= (($time > 1) ? $key.'s' : $key);
$granularity--;
}
if ($granularity == '0') { break; }
}
return ' posted '.$retval.' ago';
}
I also like the jquery timeago plugin which will automatically update all time fields on a set timer so it is up to date if the user stays on a page for a while. You would need to convert the unix time to ISO 8601 format when rendering but I believe there is a php function for that.
Simple script that takes time in seconds and works great
function twitter_time($time) {
$delta = time() - strtotime($time);
if ($delta < 60) {
return '30sec ago';
} else if ($delta < 120) {
return '1m ago';
} else if ($delta < (60 * 60)) {
return floor($delta / 60) . 'm ago';
} else if ($delta < (120 * 60)) {
return '1h ago';
} else if ($delta < (24 * 60 * 60)) {
return floor($delta / 3600) . 'h ago';
} else if ($delta < (48 * 60 * 60)) {
return '1d ago';
} else if ($delta < (86400*7)) {
return floor($delta / 86400) . 'd ago';
} else if ($delta < (2*86400*7)) {
return '1week ago';
} else if ($delta < (2592000)) {
return floor($delta / (86400*7)) . 'weeks ago';
} else if ($delta < (2*2592000)) {
return '1mon ago';
} else if ($delta < (31104000)) {
return floor($delta / 2592000) . 'mon ago';
} else if ($delta < (2*31104000)) {
return '1year ago';
} else {
return number_format(floor($delta / 31104000)) . 'years ago';
}
}