Convert hour format in seconds

Asked

Viewed 4,213 times

5

I have a value displayed by a json:

"tempoShoutcast":"03:11:48"

How can I turn this format into seconds?

2 answers

7


Using ready function

whereas the strtotime PHP uses Posix/Unix time, a very simple way is this:

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

See working on IDEONE.

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


Using calculus

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

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

See working on IDEONE.

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


To do the reverse, see here:

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

-1

And very simple only you use

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

and that’s it, it’s done.

  • 3

    Well, just to be clear, I was negative for being an exact copy of my solution, ie, this answer here is not useful (which is one of the reasons described in the downvote indicator itself)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.