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

yipeiwu_com6年前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使用strpos判断字符串中数字类型子字符串出错的解决方法 原创

本文实例讲述了php使用strpos判断字符串中数字类型子字符串出错的解决方法。分享给大家供大家参考,具体如下: 一、问题: 最近的开发中在程序代码里有一个随机数是否在给定字符串里的判断...

PHP中去掉字符串首尾空格的方法

第一种方法:通过php自带的函数 <?php /* trim 去除一个字符串两端空格, rtrim 是去除一个字符串右部空格, ltrim 是去除一个字符串左部空格。 */ ?&g...

PHP多人模块开发原理解析

PHP多人模块开发原理解析

作为世界上最“好”的语言,在web里占据着大概80%的份额,中小公司基本都说 lnmp 架构。当一个仓库开发人员大于1,20人的时候,每个人可能开发不同的模块和功能,用代码版本控制工具比...

php 根据自增id创建唯一编号类

在开发过程中,我们数据表一般都使用自增数字作为id主键,而id是数字型,不容易理解。我们把id按一定格式转为编号后,很容易根据编号知道代表的是什么内容。 例如订单表id=20160111...

php图片加水印原理(超简单的实例代码)

文字水印: 复制代码 代码如下: $w = 80; $h = 20; $im = imagecreatetruecolor($w,$h); $textcolor = imagecolor...