您的位置:首页 > 编程语言 > PHP开发

PHP将DateTime对象转化为友好时间显示的实现代码

2011-09-20 00:00 1066 查看
/** 
* 友好日期时间 
* 
* @param DateTime $datetime 日期时间 
* @param int $size 精确到位数 
* @throws \InvalidArgumentException 
* @return string 
*/ 
function friendly_date($datetime, $size=1) 
{ 
if (is_int($datetime)) { 
$datetime = new \DateTime($datetime); 
} 
if (!($datetime instanceof \DateTime)) { 
throw new \InvalidArgumentException('invalid "DateTime" object'); 
} 
$now = new \DateTime(); 
$interval = $now->diff($datetime); 
$intervalData = array( 
$interval->y, $interval->m, $interval->d, 
$interval->h, $interval->i, $interval->s, 
); 
$intervalFormat = array('年', '个月', '天', '小时', '分种', '秒'); 
foreach($intervalData as $index=>$value) { 
if ($value) { 
$intervalData[$index] = $value . $intervalFormat[$index]; 
} else { 
unset($intervalData[$index]); 
unset($intervalFormat[$index]); 
} 
} 
return implode('', array_slice($intervalData, 0, $size)); 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: