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?
Asked
Active
Viewed 1.3k times
2
-
the DateInterval class sadly has no function for that, so you will have to do the math – x4rf41 Jul 01 '13 at 15:18
-
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: [Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist) – Kermit Jul 01 '13 at 15:19
-
Is this format based on 24 hours or is can it run past 24 hours, e.g. `42:12:02`? – Jason McCreary Jul 01 '13 at 15:25
4 Answers
7

Kermit
- 33,827
- 13
- 85
- 121

mr. Pavlikov
- 982
- 5
- 7
-
-
1It takes his string as argument and returns seconds, just like he asked. Well, its up to him. – mr. Pavlikov Jul 01 '13 at 15:20
-
Maybe, provided the format can not be `42:12:02`. That is *assuming* it's based on a 24 hour clock. – Jason McCreary Jul 01 '13 at 15:22
-
It works! But if I try to get value from **mm:ss** it returns negative value. :( – Resalat Haque Jul 01 '13 at 15:31
4
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

Josh
- 2,835
- 1
- 21
- 33
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";

Patrick
- 861
- 6
- 12
1
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;
}

Jason McCreary
- 71,546
- 23
- 135
- 174