0

How can I convert a digit time into seconds?

I need to compare the time so I though that it is easier to convert the digit time to seconds and compare the seconds later on.

for example:

00:00:33
00:01:33
02:01:33
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
utdev
  • 3,942
  • 8
  • 40
  • 70
  • What do you mean by "digit time"? – Bubble Hacker Jan 05 '17 at 08:35
  • @Panda - the solution on that page while compact, is subject to inaccuracies due to the first `strtotime()` time being slightly different than the second `strtotime()` as it is processed in sequential order. It is good in most cases where precision isn't a priority and where server load is minimal. – Kraang Prime Jan 05 '17 at 08:46
  • Lots of answers, but no one questioning *why* you want to do this. Time strings are already comparable as they are. Equality and comparison operators already work as expected when applied to the strings themselves. – Phylogenesis Jan 05 '17 at 10:08

4 Answers4

2

You can write a custom parser if you are looking for precise seconds from that format.

Something like this should do the trick :

echo hhmmss2seconds("18:24:35");

function hhmmss2seconds($time) {
    $digits = explode(":", $time);
    $seconds = 0;
    $seconds = $seconds + intval($digits[0]) * 3600; // hours
    $seconds = $seconds + intval($digits[1]) * 60; // minutes
    $seconds = $seconds + intval($digits[2]); // seconds    
    return $seconds;
}
Kraang Prime
  • 9,981
  • 10
  • 58
  • 124
0

You want to use strtotime(). This converts "digit time" to Unix time.

$time_in_seconds = strtotime('00:00:33');
Kraang Prime
  • 9,981
  • 10
  • 58
  • 124
  • strange if I do this $test = strtotime(00:00:33); echo $test . '
    '; I get an unexpected ":"
    – utdev Jan 05 '17 at 08:39
  • hmm I do not get an error now but it returns me this : 1483570833 – utdev Jan 05 '17 at 08:41
  • The parameter of `strtotime()` needs to be a string so like this: `echo $test = strtotime("00:00:33");` –  Jan 05 '17 at 08:41
  • I modified it so it is encapsulated in quotes, however the result of strtotime is incorrect. [proof it is not valid](http://sandbox.onlinephpfunctions.com/code/bcbf099cd6927f664aebb6f4fbe7372d50de9afe) – Kraang Prime Jan 05 '17 at 08:42
  • http://sandbox.onlinephpfunctions.com/code/42686de4f5b1550086fa75c09c2fcabd12051263 – utdev Jan 05 '17 at 08:43
0

Try this:

echo strtotime("1970-01-01 00:00:11  UTC");
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
0

Try This its working

 <?php
    function time_to_seconds($time) { 
        list($h, $m, $s) = explode(':', $time); 
        return ($h * 3600) + ($m * 60) + $s; 
    }
    echo time_to_seconds("00:00:33");
    echo time_to_seconds("00:01:33");
    echo time_to_seconds("02:01:33");

    ?>

Thank you..

Ehsan Ilahi
  • 298
  • 5
  • 15