Convert time format in seconds

5

I have a value displayed by a json:

"tempoShoutcast":"03:11:48"

How can I make this format for seconds?

    
asked by anonymous 11.01.2017 / 07:15

2 answers

7

Using ready function

Considering that strtotime of PHP uses Posix / Unix time, a very simple way is this:

$horario = "03:11:48";
$segundos = strtotime('1970-01-01 '.$horario.'UTC');

See working at IDEONE .

This works because Posix Time is the number of seconds since January 1, 1970, so the time of day is exactly the number of seconds you are looking for.


Using Calculation

If you want to do the calculation "manually", it looks like this:

$horario = "03:11:48";
$partes = explode(':', $horario);
$segundos = $partes[0] * 3600 + $partes[1] * 60 + $partes[2];

See working at IDEONE .

We are simply dividing the time into parts by multiplying the time by 3600 (that is 60 minutes * 60 seconds), the minutes by 60, and finally adding the remaining seconds.


To do the reverse, see here:

  

How to convert seconds to the "Time: Minute: Second" format?

    
11.01.2017 / 10:37
-1

And very simple so you use

$segundos = strtotime('1970-01-01 '.$horario.'UTC');

And that's it, done.

    
11.01.2017 / 12:19