问下分钟前,小时前,天前,个月前,年前如何实现?
存在数据库的是时间戳
目前实现的方法代码
<?php
$created = time() - $value->created;
$timeArr=array(
'1'=>' 秒',
'60'=>' 分钟',
'3600'=>' 小时',
'86400'=>' 天',
'604800'=>' 星期',
'2592000'=>' 个月',
'31536000'=>' 年',
);
foreach ($timeArr as $numKey => $strValue){
if (0 != $timeNum = floor($created/(int)$numKey)){
$timeStr = $timeNum.$strValue.'前';
}
}
echo $timeStr;
;?>
这个方法就是减去时间戳后的数值循环除以数组,
这样感觉不是一个好方法,
有没有更好的方法?
/**
* 个性化日期显示
* @static
* @access public
* @param datetime $times 日期
* @return string 返回大致日期
* @example 示例 ueTime('')
*/
function ueTime($times) {
if ($times == '' || $times == 0) {
return false;
}
//完整时间戳
$strtotime = is_int($times) ? $times : strtotime($times);
$times_day = date('Y-m-d', $strtotime);
$times_day_strtotime = strtotime($times_day);
//今天
$nowdate_str = strtotime(date('Y-m-d'));
//精确的时间间隔(秒)
$interval = time() - $strtotime;
//今天的
if ($times_day_strtotime == $nowdate_str) {
//小于一分钟
if ($interval < 60) {
$pct = sprintf("%d秒前", $interval);
}
//小于1小时
elseif ($interval < 3600) {
$pct = sprintf("%d分钟前", ceil($interval / 60));
} else {
$pct = sprintf("%d小时前", floor($interval / 3600));
}
}
//昨天的
elseif ($times_day_strtotime == strtotime(date('Y-m-d', strtotime('-1 days')))) {
$pct = '昨天' . date('H:i', $strtotime);
}
//前天的
elseif ($times_day_strtotime == strtotime(date('Y-m-d', strtotime('-2 days')))) {
$pct = '前天' . date('H:i', $strtotime);
}
//一个月以内
elseif ($interval < (3600 * 24 * 30)) {
$pct = date('m月d日', $strtotime);
}
//一年以内
elseif ($interval < (3600 * 24 * 365)) {
$pct = date('m月d日', $strtotime);
}
//一年以上
else {
$pct = date('Y年m月d日', $strtotime);
}
return $pct;
}
如果是前端显示,推荐 Moment.js
时间存在数据库的当然是时间戳,但是给view层或者输出你可以做一下封装,显示为“分钟前,小时前。。”
恰逢上个项目里面有,当初另外一个同事写的,逻辑有错,我就修改了下,如下
/**
* 将时间戳转换为xx之前
* @param integer $time 与转换的时间戳
* @return string 转换后的结果,以字符串输出
* @author Scofield
* @copyright 2014/8/15
*/
function settimeval($time){
$str_1="天前";
$str_2="小时前";
$str_3="分钟前";
$str_4='秒前';
$str_5="刚刚";
$timex=time()-$time;
if($timex==0){
return $str_5;
}
elseif($timex<60){/*60秒以内显示*/
return $timex.$str_4;
}elseif(round($timex/60)<60){/*一小时以内显示xx分钟之前*/
return round($timex/60).$str_3;
}elseif(round($timex/(60*60))<24){/*一天之内显示xx小时之前*/
return round($timex/(60*60)).$str_2;
}else{/*一天以上显示多少天之前*/
return round($timex/(60*60*24)).$str_1;
}
}
你的比我的简洁多了