从typecho中剥了一段词义化时间代码并按需做了修改,在测试中发现有个问题很纳闷:(假如Unix时间戳$form与$now相差300,而它们处于不同的小时段idate(H),这样5分钟前的操作却显示为1小时前,然而在TE中却没有发现这现象^-!,现在的问题是$between0&&$between
2 回答
茅侃侃
TA贡献1842条经验 获得超21个赞
因为你剥离出来的代码对小时只对同一小时的情况进行了判断,并未判断相邻小时但相差60分钟内的情况,因此,我加了一个gapHour的变量用来代表小时差,当时间相差60分钟内,做一个if判断,如果同一小时默认处理($gapHour==0),相差一个小时时($gapHour==1),再做相应的处理。functiondateWord($from){$now=time();$between=$now-$from;$s=date('Y年m月d日H:i',$from);$fromHour=idate('H',$from);$nowHour=idate('H',$now);$gapHour=$nowHour-$fromHour;if($between>0&&$between<86400&&idate('d',$from)==idate('d',$now)){if($between<3600){if($gapHour==0){if($between<60&&idate('i',$from)==idate('i',$now)){$second=idate('s',$now)-idate('s',$from);if(0==$second){return'刚刚'; }else{return''.$second.'秒前'; }}$min=idate('i',$now)-idate('i',$from);return''.$min.'分钟前'; }elseif($gapHour==1){if($between<60&&idate('i',$from)==idate('i',$now)){$second=idate('s',$now)+(60-idate('s',$from));if(0==$second){return'刚刚'; }else{return''.$second.'秒前'; }}$min=idate('i',$now)+(60-idate('i',$from));return''.$min.'分钟前'; }}$hour=idate('H',$now)-idate('H',$from);return''.$hour.'小时前'; }}
德玛西亚99
TA贡献1770条经验 获得超3个赞
额一来大段代码看着头晕,二来官方现在也不是很推荐用date()函数来操作时间对象了,所以我把整个的代码都改写了一下:functiondateWord($from,$now){$timezone=newDateTimeZone('Asia/Shanghai');$now=newDateTime($now,$timezone);$from=newDateTime($from,$timezone);$between=$now->diff($from);if(!$between->invert)returnfalse;/**如果超过了一年**/if($between->y)return$from->format('Y年m月d日');/**一年内大于七天**/if($between->days>6)return$from->format('n月j日');/**一个礼拜内但是大于两天**/if($between->days>1)return$between->format('%d天前');/**如果是昨天**/if($between->days)return$from->format('昨天H:i');/**如果一天之内超过一个小时**/if($between->h>1)return$between->format('%h小时前');if($between->i>1)return$between->format('%i分钟前');return$between->s?$between->format('%s秒前'):'刚刚';}functiondateWordToHtml($from,$now='now'){$dateWord=dateWord($from,$now);$from=newDateTime($from,newDateTimeZone('Asia/Shanghai'));$fromWord=$from->format('Y年m月d日H:i');return"$dateWord"; }echodateWordToHtml("2014/4/149:32");dateWord()函数对应的是Typecho原版的返回,dateWordToHtml()函数则是对应你修改的那个函数(另外新建一个函数主要是方便其他人参考调用)。
添加回答
举报
0/150
提交
取消