如何在PHP中将unix时间戳转换为ISO8601时间戳?

时间:2010-03-18 17:02:07

标签: php mysql timestamp

我正在尝试从mysql中提取unix时间戳并将其转换为ISO8601时间戳。我需要它,以便将日期格式化为类似Facebook(或堆栈溢出类似:) '30分钟前',而不是显示确切的日期和时间。有没有人处理过它?

2 个答案:

答案 0 :(得分:17)

$timestamp = '1268932078';

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

但如果您不想自己动手,可以使用内置函数来帮助您,例如:DateTime::diff

答案 1 :(得分:4)

Facebook赞时间格式:

  

的时差功能   输出在Facebook的中传递的时间    style: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