PHP比较两个时间戳相差天时分秒
一、效果
二、代码
public function test4(){$time = time();$beforeTime = $time - mt_rand(1000, 9999);$afterTime = $time + mt_rand(1000, 9999);$array = [['desc' => '相等的情况:','time' => $time,'see_all' => true,],['desc' => '<i>详情信息-之前:</i>','time' => $beforeTime,'see_all' => true,],['desc' => '<i>粗略信息-之前:</i>','time' => $beforeTime,'see_all' => false,],['desc' => '详情信息-之后:','time' => $afterTime,'see_all' => true,],['desc' => '粗略信息-之后:','time' => $afterTime,'see_all' => false,]];foreach ($array as $value){echo $value['desc'] . ' [ ' . $this->beforeTime($value['time'], $value['see_all']) . ' ]<br/>';}die();}/*** @param $time 待计算的时间戳* @param bool $seeAll 是否返回详细信息:true 是; false 否* @return string 结果数据*/public function beforeTime($time, $seeAll = true){$nowTime = time();if ($time == $nowTime){return '时间相等,比较无意义...';}$suffix = $nowTime > $time ? '前' : '后'; //判断是之前还是之后$diffTime = abs($nowTime - $time); //求绝对值$day = (int)($diffTime / 86400); //天$hour = (int)($diffTime % 86400 / 3600); //时$minute = (int)($diffTime % 86400 % 3600 / 60); //分$second = (int)($diffTime % 86400 % 3600 % 60); //秒//从大到小,键值不能互换,如果值为0会存在键覆盖问题$timeArray = ['天' => $day,'时' => $hour,'分' => $minute,'秒' => $second];$string = '';foreach ($timeArray as $key => $value){if ($value){ //数据不为空,则拼接$string .= $this->addZero($value) . $key;if (!$seeAll){break;}}}return $string . $suffix;}public function addZero($data){return ($data >= 10) ? $data : ('0' . $data);}