如何将时间格式HH:MM:SS
转换为固定的秒数?
PS Time有时可能MM:SS
仅采用格式。
Answers:
不需要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;
如果您不想使用正则表达式:
$str_time = "2:50";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($hours) ? $hours * 3600 + $minutes * 60 + $seconds : $minutes * 60 + $seconds;
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
应该是$time_seconds = isset($hours) ? $hours * 3600 + $minutes * 60 + $seconds : $minutes * 60 + $seconds;
我认为最简单的方法是使用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()
也可以用于解析日期和时间:
$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
如果您要MM:SS
使用strtotime()
或来解析格式,date_parse()
则将失败(date_parse()
在strtotime()
和中使用DateTime
),因为当您输入类似xx:yy
parser的格式时,就会假设它是HH:MM
and not MM:SS
。我建议您检查格式,00:
如果只有,请添加MM:SS
。
demo strtotime()
demo date_parse()
如果你有时间超过24,那么你可以使用下面的函数(它会为工作MM:SS
和HH:MM:SS
格式):
function TimeToSec($time) {
$sec = 0;
foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v;
return $sec;
}
strtotime()
不允许小时数超过24-使用25或更高的值将返回“ false”。
array_reverse
和爆炸上:
然后通过使一个多行程foreach
和另一个pow
(使得两个HH:MM和HH:MM:SS无功能的变形例的工作)是天才的行程。卓越的代码。我很难想象一个更有效的例子。谢谢!
$time = 00:06:00;
$timeInSeconds = strtotime($time) - strtotime('TODAY');
用伪代码:
split it by colon
seconds = 3600 * HH + 60 * MM + SS
尝试这个:
$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;
<?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];
function time2sec($time) {
$durations = array_reverse(explode(':', $item->duration));
$second = array_shift($durations);
foreach ($durations as $duration) {
$second += (60 * $duration);
}
return $second;
}
echo time2sec('4:52'); // 292
echo time2sec('2:01:42'); // 7302