摸鱼应该是为了创造价值。
又到了搞活动的时间,无论活动预热还是活动进行到结束都需要有时间的控制,有时候需要给用户展示倒计时,自己写了个计算两个日期时间倒计时的函数:
/** * 算一下时间剩下x天y小时z分s秒 * @author blog@alipay168.cn * @param $time1 int|string * @param $time2 int|string * @return array */ function cal_diff_time($time1, $time2) { if (!is_numeric($time1)) { $time1 = strtotime($time1); } if (!is_numeric($time2)) { $time2 = strtotime($time2); } $diffTime = $time2 > $time1 ? $time2 - $time1 : $time1 - $time2;//距离还有x秒 $diffDay = intval($diffTime / 86400);//天 $diffHour = intval($diffTime % 86400 / 3600);//小时 $diffMinute = intval($diffTime % 86400 % 3600 / 60);//分钟 $diffSecond = $diffTime % 86400 % 3600 % 60;//秒 $format = sprintf('%s天%s时%s分%s秒', $diffDay, $diffHour, $diffMinute, $diffSecond); return [ 'allSecond' => $diffTime, 'day' => $diffDay, 'hour' => $diffHour, 'minute' => $diffMinute, 'second' => $diffSecond, 'format' => $format ]; } //实例1 print_r(cal_diff_time('2020-05-31 23:59:59','2021-05-31 23:59:59')); //返回效果 Array ( [allSecond] => 31536000 [day] => 365 [hour] => 0 [minute] => 0 [second] => 0 [format] => 365天0时0分0秒 ) //实例2 print_r(cal_diff_time(time(),'2021-05-31 23:59:59')); //返回 Array ( [allSecond] => 2708312 [day] => 31 [hour] => 8 [minute] => 18 [second] => 32 [format] => 31天8时18分32秒 )
说明:
参数可以是int类型的时间戳或者完整的字符串类型;
allSecond-目前相差的秒数
day-多少天
hour-多少小时
minute-多少分钟
second-多少秒
format-字符串拼接返回剩余时间