Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a "HH:MM:SS" string to seconds with PHP?

Is there a native way of doing "HH:MM:SS" to seconds with PHP 5.3 rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?


For example in Python you can do :

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

like image 871
benjisail Avatar asked Jan 05 '11 14:01

benjisail


People also ask

How do you convert HH MM SS to seconds?

To convert hh:mm:ss to seconds:Convert the hours to seconds, by multiplying by 60 twice. Convert the minutes to seconds by multiplying by 60 . Sum the results for the hours and minutes with the seconds to get the final value.

How to convert string into time in php?

Code for converting a string to dateTime $input = '06/10/2011 19:00:02' ; $date = strtotime ( $input ); echo date ( 'd/M/Y h:i:s' , $date );

How convert seconds to hours minutes and seconds in PHP?

php //PHP program to convert seconds into //hours, minutes, and seconds $seconds = 6530; $secs = $seconds % 60; $hrs = $seconds / 60; $mins = $hrs % 60; $hrs = $hrs / 60; print ("HH:MM:SS-> " . (int)$hrs .


1 Answers

I think the easiest method would be to use strtotime() function:

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

demo


Function date_parse() can also be used for parsing date and time:

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

demo

like image 125
Glavić Avatar answered Oct 13 '22 00:10

Glavić