php - convert Hour:Minute:Second. to second
13,047
Solution 1
You can try using
strtotime('00:02:05') - strtotime('today'); //125
Solution 2
You could use the explode function in PHP:
function seconds($time){
$time = explode(':', $time);
return ($time[0]*3600) + ($time[1]*60) + $time[2];
}
Example: http://codepad.org/gAjZGtq3
Solution 3
strtotime
could help. Documentation.
Alternatively,
<?php
$parts = explode(":", $my_str_time); //if you know its safe
$answer = ($parts[0] * 60 * 60 + $parts[1] * 60 + $parts[2]) . "s";
Solution 4
There may be something in the DateTime
class. But there is no single method. In addition, you'd need to convert your format to a date time object, then back again.
It's trivial to write your own:
function toSeconds($hours, $minutes, $seconds) {
return ($hours * 3600) + ($minutes * 60) + $seconds;
}
Comments
-
Resalat Haque almost 2 years
I need to convert Hour:Minute:Second to second (for example 00:02:05 = 125s). Is there any build in function in PHP to this or need to do some math?
-
Jason McCreary almost 11 yearsI don't believe this is what the user is asking.
-
mr. Pavlikov almost 11 yearsIt takes his string as argument and returns seconds, just like he asked. Well, its up to him.
-
Jason McCreary almost 11 yearsMaybe, provided the format can not be
42:12:02
. That is assuming it's based on a 24 hour clock. -
Resalat Haque almost 11 yearsIt works! But if I try to get value from mm:ss it returns negative value. :(