2010-03-18 163 views
12

我想从MySQL中提取unix时间戳并将其转换为ISO8601时间戳。我需要它来将日期的格式设置为类似Facebook的格式(或“30分钟前的堆栈溢出”),而不是显示确切的日期和时间。有人处理过吗?如何将PHP中的unix时间戳转换为ISO8601时间戳?

+0

这里是一个不错的jQuery库吧,是你正在使用的一个? http://github.com/rmm5t/jquery-timeago – joar

回答

16
$timestamp = '1268932078'; 

$iso8601 = date('c', $timestamp); 

但也有内置的功能,以帮助你这个,如果你不希望推出自己的,例如:DateTime::diff

3

的Facebook就像时间格式:

时差功能 输出在Facebook的 风格经过的时间:1天前,或4个月前。

http://www.php.net/manual/en/function.time.php#89415

function nicetime($date) 
{ 
    if(empty($date)) { 
     return "No date provided"; 
    } 
$periods = array("second","minute","hour","day","week","month","year","decade"); 
$lengths = array("60","60","24","7","4.35","12","10"); 
$now = time(); 
$unix_date = strtotime($date); 
    if(empty($unix_date)) {  
     return "Bad date"; 
    } 
    if($now > $unix_date) {  
     $difference  = $now - $unix_date; 
     $tense   = "ago"; 

    } else { 
     $difference  = $unix_date - $now; 
     $tense   = "from now"; 
    }  
    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 
     $difference /= $lengths[$j]; 
    } 
    $difference = round($difference); 
    if($difference != 1) { 
     $periods[$j].= "s"; 
    } 
    return "$difference $periods[$j] {$tense}"; 
} 

// convert timestamp to date ISO8601 
$timestamp = date('c', '1268932078'); 
// convert to nice date 
echo nicetime($timestamp); //40 years ago 
+0

这不回答这个问题。 – bdsl

+0

@ bdsl:你是对的,我没有读过这个问题,我应该这么好,顺便说一句,我已经更新了答案。感谢报告... –