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

2022-08-30 08:11:20

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

附言时间有时可能仅采用格式。MM:SS


答案 1

无需执行任何操作: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($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

答案 2

我认为最简单的方法是使用函数: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'];

演示


如果您将解析格式,否则它将失败(在 和 中使用),因为当您输入格式时,如解析器假定它是而不是 。我建议检查格式,如果您只有.c,请加前缀。MM:SSstrtotime()date_parse()date_parse()strtotime()DateTimexx:yyHH:MMMM:SS00:MM:SS

demo strtotime()
demo date_parse()


如果您的小时数超过 24 小时,则可以使用下一个函数(它将适用于和格式化):MM:SSHH:MM:SS

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

演示


推荐