Home >Backend Development >PHP Tutorial >How to Convert HH:MM:SS Time to Total Seconds in PHP?
Converting Time in HH:MM:SS Format to Seconds
Converting time in HH:MM:SS format to a flat seconds number is a common task in programming. This can be achieved using a straightforward procedure.
Solution:
There are two approaches to this conversion:
Approach 1: Using Regular Expressions
Add leading zeros to the MM:SS format if it exists. This can be done using regular expressions:
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00::", $str_time);
Extract hours, minutes, and seconds using sscanf:
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
Approach 2: Without Regular Expressions
For time in MM:SS format, use the following:
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds); $time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
For time in HH:MM:SS format, directly extract hours, minutes, and seconds using sscanf:
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds); $time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
Example Usage:
$str_time = "23:12:95"; $time_seconds = $hours * 3600 + $minutes * 60 + $seconds; echo $time_seconds; // Output: 83575
The above is the detailed content of How to Convert HH:MM:SS Time to Total Seconds in PHP?. For more information, please follow other related articles on the PHP Chinese website!