[php] Convert time in HH:MM:SS format to seconds only?

How to turn time in format HH:MM:SS into a flat seconds number?

P.S. Time could be sometimes in format MM:SS only.

This question is related to php time

The answer is


I think the easiest method would be to use strtotime() function:

$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


Function date_parse() can also be used for parsing date and time:

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

demo


If you will parse format MM:SS with strtotime() or date_parse() it will fail (date_parse() is used in strtotime() and DateTime), because when you input format like xx:yy parser assumes it is HH:MM and not MM:SS. I would suggest checking format, and prepend 00: if you only have MM:SS.

demo strtotime() demo date_parse()


If you have hours more than 24, then you can use next function (it will work for MM:SS and HH:MM:SS format):

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

demo


In pseudocode:

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

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

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

Try this:

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

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

Simple

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

You can use the strtotime function to return the number of seconds from today 00:00:00.

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