php暂停和继续时间计算
文章描述:
有开始和结束时间,中间有多次暂停,怎么计算时间差?
一、计算两个时间相差
<?
$stop_data = NULL;
if(strlen($stop_data) == 0) {
echo $sum_time = $end_time - $start_time;
exit;
return $sum_time;
}
二、暂停和继续
$data = [
['date_time'=>'2025-05-13 16:00:10','stop'=>1], // 暂停
['date_time'=>'2025-05-13 16:00:20','stop'=>0], // 继续 10秒
['date_time'=>'2025-05-13 16:00:40','stop'=>1], // 暂停
// ['date_time'=>'2025-05-13 16:00:45','stop'=>0], // 继续 5秒
];
$data['stop_data'] = serialize($data);
$stop_data = unserialize($data['stop_data']);
// 有一次暂停
if(count($stop_data) == 1){
// echo $stop_data[0]['date_time'];
echo $sum_time = strtotime($stop_data[0]['date_time']) - $start_time;
// return $sum_time;
}
// 多次暂停和继续
if (count($stop_data) % 2 == 0) {
// 继续
$arr = [];
foreach ($stop_data as $k=>$v)
{
$k + 1;
if ($k % 2 == 0) {
}else{
$time = strtotime($stop_data[$k]['date_time']) - strtotime($stop_data[$k-1]['date_time']);
array_push($arr,$time);
}
}
$stop_time = array_sum($arr);
echo '暂停时间:'.$stop_time."<br/>";
$sum_time = $end_time - $start_time - $stop_time;
echo "总时间:".$sum_time;
} else {
// 暂停 echo " 是单数";
// 最后一次暂停作为结束时间
$lastIndex = count($stop_data) - 1; // 或者使用 array_key_last($array) (PHP >= 7.3)
$lastSubArray = $stop_data[$lastIndex];
$end_time = strtotime($lastSubArray['date_time']);
// 一次最后一次暂停
$list = $stop_data;
$lastKey = end(array_keys($list));
unset($list[$lastKey]);
$arr = [];
foreach ($list as $k=>$v)
{
$k + 1;
if ($k % 2 == 0) {
}else{
$time = strtotime($stop_data[$k]['date_time']) - strtotime($stop_data[$k-1]['date_time']);
array_push($arr,$time);
}
}
$stop_time = array_sum($arr);
echo '暂停时间:'.$stop_time."<br/>";
$sum_time = $end_time - $start_time - $stop_time;
echo "总时间1:".$sum_time;
}
时间戳转时分秒
function secondsToTime($seconds) {
if(!$seconds)
return '00:00:00';
$seconds = intval(trim($seconds));
$hours = floor($seconds / 3600);
$minutes = floor(($seconds % 3600) / 60);
$secs = $seconds % 60;
// 格式化输出,确保始终有两位数
$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$secs = str_pad($secs, 2, '0', STR_PAD_LEFT);
return "{$hours}:{$minutes}:{$secs}";
}
发布时间:2025/06/04
发表评论