87

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.

arogachev
  • 33,150
  • 7
  • 114
  • 117
CodeOverload
  • 47,274
  • 54
  • 131
  • 219

10 Answers10

149

No need to explode anything:

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

And if you don't want to use regular expressions:

$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;
  • 1
    When using time functions I had to mess around with timezones to get it right, but this is much simpler. – datagutten Aug 20 '17 at 08:52
  • 1
    Mistake in the last line:`$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;` Should be `$time_seconds = isset($hours) ? $hours * 3600 + $minutes * 60 + $seconds : $minutes * 60 + $seconds;` – Andrew Lazarus Nov 12 '17 at 20:40
  • Actually, shouldn't the last line be: isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes; If there is no hour, then need to treat hours as minutes and minutes as seconds. For example: 10:01 should be 601 seconds. – rlorenzo Feb 27 '21 at 05:36
  • @rlorenzo: Yes. Someone edited my answer and broke it. –  Feb 27 '21 at 14:59
  • Colons do not need to be escaped in the pattern. `[\d]` is more simply expressed as `\d`. – mickmackusa Aug 06 '22 at 02:20
117

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

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • 6
    `strtotime()` does not allow the hours go beyond 24 - using 25 or higher will return "false". – Sven Jul 18 '15 at 18:33
  • 2
    Your 3rd answer for times over 24 hours is exactly what I needed. The `array_reverse` and explode on `:` then causing one more trip through the `foreach` and another `pow` (so that both *hh:mm* AND *hh:mm:ss* work without modification of the function) is a stroke of genius. Code par excellence. I can hardly imagine a more efficient example. Thanks! – FirstFraktal Aug 24 '15 at 04:26
  • @Glavić Some how helps me too – Abdulla Nilam Jul 14 '16 at 20:01
  • What if it is containing dot `.` like this `00:20:55.60000`? I tried to post a question, but there seems a problem. – Ari Jan 25 '17 at 11:22
  • @KeepMove: remove microseconds, on round them to seconds part. – Glavić Jan 25 '17 at 15:32
  • 1
    I just looked at the first answer, and thought, what if I used the Unix epoch... up vote from me! – Exit Oct 05 '17 at 22:04
  • 1
    The third option works for every valid format I could throw at it. – Synetech Oct 15 '19 at 04:45
  • @Ari The third option works with milliseconds and nanoseconds, too, as it's just a comma-value. It's a really interesting way to solve this... – sjngm Nov 13 '20 at 09:40
  • 1
    The first option `$seconds = strtotime("1970-01-01 $time UTC");` should be the shortest answer and the accepted one. The use of `1970-01-01` is genial! – user2342558 Jun 03 '21 at 08:36
17
    $time = 00:06:00;
    $timeInSeconds = strtotime($time) - strtotime('TODAY');
sparsh turkane
  • 1,165
  • 12
  • 13
12

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

$seconds= strtotime($time) - strtotime('00:00:00');
Ivan86
  • 5,695
  • 2
  • 14
  • 30
mehdi jalilvand
  • 450
  • 4
  • 12
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Filnor Jan 23 '18 at 12:19
6

In pseudocode:

split it by colon
seconds = 3600 * HH + 60 * MM + SS
CanSpice
  • 34,814
  • 10
  • 72
  • 86
  • 6
    As he wrote, it's pseudocode. "Pretend code" to explain how something could be done. – iamsim.me Jan 29 '11 at 00:10
  • 2
    It doesn't matter whether it's pseudocode or not because the question requires supporting MM:SS format which this answer does not. – Synetech Oct 15 '19 at 04:48
5

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;
Glavić
  • 42,781
  • 13
  • 77
  • 107
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • I love it! $time = "01:23:54:21:30:10" gives me an answer of 1087421410 seconds. – Roger Halliburton Jan 29 '11 at 00:33
  • 2
    Try it now. Ofcourse you can pass something like "898989:8989898:899899", but I assume basic validations will be done on the time entered before code reached to the seconds calculation. – Chandu Jan 29 '11 at 00:37
2

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;
}
midan888
  • 179
  • 6
1
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
kodmanyagha
  • 932
  • 12
  • 20
  • This answer is cleanest, except for `$item->duration`, which should just be replaced by `$time`. And it should probably do some casting. – John Green Jul 28 '21 at 02:12
0

On Windows 32 bit PHP version: 7.2.31 i get some error on all versions posted here. If the time was 00:00:00 or 00:00:00 the zeros 00 were returned and used as "" empty string, and calculation with empty string returns error "A Non WELLNUMERIC blabla.

This Works also with more then 24hours:

function TimeToSec(string $time) {
   $timearray = explode(":",$time);
   $hours   = (int)$timearray[0];
   $minutes = (int)$timearray[1];
   $seconds = (int)$timearray[2];;

  //echo "Hours: " . $hours ."<br>";
   //echo "minutes: " . $minutes ."<br>";
   //echo "seconds: " . $seconds ."<br>";

   $value = ($hours * 3600) + ($minutes * 60) + $seconds;
return $value;
}

echo TimeToSec("25:00:30");
Frost
  • 11
  • 2
-1
<?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];
iamsim.me
  • 560
  • 4
  • 17