2

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?

Resalat Haque
  • 31
  • 1
  • 1
  • 4
  • 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 Answers4

7

You can try using

strtotime('00:02:05') - strtotime('today'); //125

Demo

Kermit
  • 33,827
  • 13
  • 85
  • 121
mr. Pavlikov
  • 982
  • 5
  • 7
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