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

时间:2011-01-29 00:04:19

标签: php time

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

P.S。时间有时仅为格式MM:SS

9 个答案:

答案 0 :(得分:111)

无需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;

答案 1 :(得分:87)

我认为最简单的方法将使用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;

demo


函数date_parse()也可用于解析日期和时间:

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

demo


如果您要使用MM:SSstrtotime()解析格式date_parse(),它将失败(date_parse()strtotime()中使用DateTime),因为当您输入格式如xx:yy时,解析器会假定它是HH:MM而不是MM:SS。我建议检查格式,如果你只有00:,请提前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;
}

demo

答案 2 :(得分:5)

在伪代码中:

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

答案 3 :(得分:5)

试试这个:

$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;

答案 4 :(得分:4)

    $time = 00:06:00;
    $timeInSeconds = strtotime($time) - strtotime('TODAY');

答案 5 :(得分:2)

您可以使用strtotime函数返回today 00:00:00的秒数。

$seconds= strtotime($time) - strtotime('00:00:00');

答案 6 :(得分:1)

简单

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;
}

答案 7 :(得分:0)

<?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];

答案 8 :(得分:0)

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
相关问题