将HH:MM:SS格式的时间转换为仅秒?

如何将HH:MM:SS格式的时间转换为平坦的秒数?

PS时间有时可能只有MM:SS格式。

不需要explode任何东西:

 $str_time = "23:12:95"; $str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time); sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds); $time_seconds = $hours * 3600 + $minutes * 60 + $seconds; 

如果你不想使用正则expression式:

 $str_time = "2:50"; sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds); $time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes; 

我认为最简单的方法是使用strtotime()函数:

 $time = '21:30:10'; $seconds = strtotime("1970-01-01 $time UTC"); echo $seconds; // same with objects (for php5.3+) $time = '21:30:10'; $dt = new DateTime("1970-01-01 $time", new DateTimeZone('UTC')); $seconds = (int)$dt->getTimestamp(); echo $seconds; 

演示


函数date_parse()也可以用于parsingdate和时间:

 $time = '21:30:10'; $parsed = date_parse($time); $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second']; 

演示


如果用strtotime()date_parse()parsing格式MM:SS ,将失败(在strtotime()DateTime使用date_parse() ),因为当你input格式如xx:yyparsing器假定是HH:MM和不是MM:SS 。 我会build议检查格式,并预先00:如果你只有MM:SS

演示 strtotime() 演示 date_parse()


如果你的时间超过24小时,你可以使用下一个function(它将适用于MM:SSHH:MM:SS格式):

 function TimeToSec($time) { $sec = 0; foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v; return $sec; } 

演示

尝试这个:

 $time = "21:30:10"; $timeArr = array_reverse(explode(":", $time)); $seconds = 0; foreach ($timeArr as $key => $value) { if ($key > 2) break; $seconds += pow(60, $key) * $value; } echo $seconds; 

在伪代码中:

 split it by colon seconds = 3600 * HH + 60 * MM + SS 

简单

 function timeToSeconds($time) { $timeExploded = explode(':', $time); if (isset($timeExploded[2])) { return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2]; } return $timeExploded[0] * 3600 + $timeExploded[1] * 60; } 
  $time = 00:06:00; $timeInSeconds = strtotime($time) - strtotime('TODAY'); 
 <?php $time = '21:32:32'; $seconds = 0; $parts = explode(':', $time); if (count($parts) > 2) { $seconds += $parts[0] * 3600; } $seconds += $parts[1] * 60; $seconds += $parts[2]; 
 $time="12:10:05"; //your time echo strtotime("0000-00-00 $time")-strtotime("0000-00-00 00:00:00"); 
 // HH:MM:SS or MM:SS echo substr($time , "-2"); // returns last 2 chars : SS