PHP将DateTime对象转化为友好时间显示的实现代码
作者:bea
代码如下: /** * 友好日期时间 * * @param DateTime $datetime 日期时间 * @param int $size 精确到位数 * @throws InvalidArgumentException * @return string */ function friendly_date($datetime, $size=1) { if (is_int($datetime)) { $datetime = new DateTi
代码如下:
/**
* 友好日期时间
*
* @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));
}
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- php 文件缓存函数
- php数字转汉字代码(算法)
- PHP判断远程url是否有效的几种方法小结
- php下利用curl判断远程文件是否存在的实现代码
- PHP下判断网址是否有效的代码
- Admin generator, filters and I18n
- 如何在symfony中导出为CSV文件中的数据
- php中时间轴开发(刚刚、5分钟前、昨天10:23等)
- linux iconv方法的使用
- linux系统上支持php的 iconv()函数的方法
- php中mysql模块部分功能的简单封装
- php XMLWriter类的简单示例代码(RSS输出)
- 简单的PHP缓存设计实现代码
- php利用iframe实现无刷新文件上传功能的代码
- php json_encode奇怪问题说明
- PHP安全配置详细说明
- 使用PHP遍历文件夹与子目录的函数代码
- 新浪微博API开发简介之用户授权(PHP基础篇)
- PHP+MYSQL会员系统的登陆即权限判断实现代码