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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

/**
* 友好日期时间
*
* @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中Ioc(控制反转)和Di(依赖注入)

先看一个例子: <?php class A { public $b; public $c; public function A() { //TODO }...

php遍历目录输出目录及其下的所有文件示例

好多次笔试都会遇到这个问题,所以特意给写了出来 复制代码 代码如下: function my_scandir($dir){ $files=array(); if(is_dir($dir)...

PHP的反射机制实例详解

本文实例讲述了PHP的反射机制。分享给大家供大家参考,具体如下: 介绍: PHP5添加了一项新的功能:Reflection。这个功能使得phper可以reverse-engineer c...

SWFUpload与CI不能正确上传识别文件MIME类型解决方法分享

解决方案如下,其它框架雷同。 源代码(/system/libraries/upload.php 199 line) $this->file_type = preg_replace(...

PHP中的替代语法介绍

今天看了一下wordpress的代码,里面有些少见的php替代语法, 复制代码 代码如下: <?php else : ?>    ...