Home >Backend Development >PHP Tutorial >How Can I Convert HH:MM:SS Time Strings to Total Seconds in PHP?
Transforming Time: HH:MM:SS to Pure Seconds
When working with time, the need often arises to convert a time string in the HH:MM:SS format into a simple integer representing the total number of seconds. To achieve this, one can employ various methods, such as the one showcased below.
Solution:
The provided solution leverages Perl-style regular expressions and the sscanf() function to dissect the time string and extract the hours, minutes, and seconds information. It then uses simple arithmetic to calculate the total number of seconds.
By using preg_replace() to pad the string with leading zeros, the code ensures a consistent format for the sscanf() function to parse regardless of the input string format. This avoids the need for additional error handling or special cases for partial times like "MM:SS."
Here's the code in action:
$str_time = "23:12:95"; $str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00::", $str_time); sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds); $time_seconds = $hours * 3600 + $minutes * 60 + $seconds; echo $time_seconds; // Output: 83615
By using this approach, you can effortlessly convert time strings in HH:MM:SS format to their equivalent total seconds representation.
The above is the detailed content of How Can I Convert HH:MM:SS Time Strings to Total Seconds in PHP?. For more information, please follow other related articles on the PHP Chinese website!