例如,当您提交帖子时,可能会说“提前1秒”。如果它是2周大,它会说。 SO和Reddit是否编写了这些或者是否有一个PHP / SQL函数将日期转换为更易读的相关格式?
答案 0 :(得分:2)
我强烈建议查看John Resig漂亮的日期库:
http://ejohn.org/blog/javascript-pretty-date/
如该博客文章所示,您可以执行以下操作:
prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
prettyDate("2007-12-15T22:24:17Z") // => undefined
答案 1 :(得分:1)
它们被称为模糊日期/时间,JavaScript和PHP有很多库。
答案 2 :(得分:0)
有很多方法可以做到这一点,但是如果你想使用php,那么这个函数将以一种很好的方式输出它只需将一个unix时间戳放在
中function timeDiffrence($from, $to = null){
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
" Years" => 29030400, // seconds in a year (12 months)
" Months" => 2419200, // seconds in a month (4 weeks)
" Weeks" => 604800, // seconds in a week (7 days)
" Days" => 86400, // seconds in a day (24 hours)
" Hours" => 3600, // seconds in an hour (60 minutes)
" Minute" => 60, // seconds in a minute (60 seconds)
" Second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? (" from now") : (" "));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= "".$and.intval($diff / $mult)."".$unit.((intval($diff / $mult) == 1) ? (", ") : ("'s, "));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(""));
if($output =='go' || $output ==' ago'){$output = 'A few secs ago';}
return 'Posted '.str_ireplace('1 Days','1 Day',trim($output,', ')).' ago';
}