Sometimes, we want to convert time in HH:MM:SS format to seconds only with PHP.
In this article, we’ll look at how to convert time in HH:MM:SS format to seconds only with PHP.
How to convert time in HH:MM:SS format to seconds only with PHP?
To convert time in HH:MM:SS format to seconds only with PHP, we can use the sscanf
function.
For instance, we write
$str_time = "2:50";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds)
? $hours * 3600 + $minutes * 60 + $seconds
: $hours * 60 + $minutes;
to call sscanf
with $str_time
, "%d:%d:%d"
, $hours
, $minutes
, $seconds
to get the hours, minutes, and seconds from $str_time
and assign them to $hours
, $minutes
, and $seconds
.
Then we add them together with $hours * 3600 + $minutes * 60 + $seconds
is $seconds
is set.
Otherwise, we get the sum with $hours * 60 + $minutes
.
Conclusion
To convert time in HH:MM:SS format to seconds only with PHP, we can use the sscanf
function.