900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > PHP比较两个时间戳相差天时分秒

PHP比较两个时间戳相差天时分秒

时间:2023-08-23 08:17:06

相关推荐

PHP比较两个时间戳相差天时分秒

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);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。