tags:

views:

126

answers:

6

On our site, we have a lot of swimming times that we would like to convert to seconds. i.e. 1:23:33.03 or 58:22.43. Is there a PHP function that can do this? A MySQL function?

A: 

Strtotime is what you need. You get a Unix timestamp which in this case would be the number of seconds.

Sergi
Not so much looking for a time of day, looking for a conversion of a swimming time in HH:MM:SS.XX or MM:SS.XX to total seconds
Brian
Again, you could just use strtotime to convert between timelaps to total seconds.
Sergi
+2  A: 
function time2seconds($time='00:00:00')
{
    list($hours, $mins, $secs) = explode(':', $time);
    return ($hours * 3600 ) + ($mins * 60 ) + $secs;
}

From here.

MySQL also has TIME_TO_SEC()

jasonbar
I probably wouldn't name it like that, but it's the right idea.
Tobias Cohen
Why the downvote?
jasonbar
@jasonbar: you stole my answer
zerkms
heh, I guess did..
jasonbar
Downvote for stealing another person's answer!
St. John Johnson
actually i downvoted not for stealing. and i post my comment about "stealing" before i saw his "Why the downvote?". so my comment is not answer to that. and just after that i changed my vote to +1 to be polite ;-)
zerkms
A: 

I am a little confused but I think that you mean. 1 hour, 23 minuts and 23.03 seconds.

this is not difficult to do. I made this PHP function that does that. My php server doesn't want to start up, so I couldn't test it, but I think it should work.

function ConvertTimeToSeconds($T)
{
    $exp = explode(":",$T);
    $c = count($exp);
    $r = 0;
    if ($c == 2)
    {
        $r = (((int)$exp[0]) * 60) + ((int)$exp[1]);
    }else{
        $r = (((int)$exp[0]) * 3600) + (((int)$exp[1]) * 60) + ((int)$exp[2]);
    } 

    return $r;
}

ConvertTimeToSeconds("1:23:33.03");
Aaron de Windt
+3  A: 

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_time-to-sec

mysql> SELECT TIME_TO_SEC('22:23:00');
    -> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
    -> 2378
zerkms
@zerkms - what about fractions of seconds?
martin clayton
nothing. mysql hasn't fractions at it's time/datetime datatypes :-S
zerkms
Actually, MySQL will allow you to specify microseconds in date/time literals passed to the various date/time functions, and as a return value from some of those functions. It just won't store them in any DATE, DATETIME or TIMESTAMP columns.
Rob
A: 

so if mysql without fractions not appropriate solution - here is another mine

$time = '1:23:33.03';

$parts = explode(':', $time);

$seconds = 0;

foreach ($parts as $i => $val) {
    $seconds += $val * pow(60, 2 - $i);
}

echo $seconds;
zerkms
+1  A: 

Use the following program for converting time to seconds in php.

<?php
function time_to_sec($time) {
    $hours = substr($time, 0, -6);
    $minutes = substr($time, -5, 2);
    $seconds = substr($time, -2);

    return $hours * 3600 + $minutes * 60 + $seconds;
}

$result=time_to_sec('12:25:59');
echo $result;
?>
rekha_sri