How to convert the string "HH: MM: SS" in seconds using PHP?

Is there any own way to do "HH:MM:SS" to seconds with PHP 5.3 instead of doing a colon separation and multiplying each section by the corresponding number to calculate the seconds?


For example, in Python you can:

 string time = "00:01:05"; double seconds = TimeSpan.Parse(time).TotalSeconds; 

+7
source share
4 answers

Quick way:

 echo strtotime('01:00:00') - strtotime('TODAY'); // 3600 
+22
source

This should do the trick:

 list($hours,$mins,$secs) = explode(':',$time); $seconds = mktime($hours,$mins,$secs) - mktime(0,0,0); 
+7
source

I think the simplest method will use the strtotime() function:

 $time = '21:30:10'; $seconds = strtotime("1970-01-01 $time UTC"); echo $seconds; 

demo


The date_parse() function can also be used to pars date and time:

 $time = '21:30:10'; $parsed = date_parse($time); $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second']; 

demonstration

+4
source

Unfortunately, no - since PHP is not strongly typed, there is no concept of the type of time and, therefore, there is no means to convert between such a string and the value of "seconds".

Thus, in practice, people often split the line and propagate each section, as you mentioned.

+2
source

All Articles