Home >Backend Development >PHP Tutorial >How to Convert HH:MM:SS or MM:SS Time Strings to Seconds in Programming?
Converting time strings in HH:MM:SS or MM:SS format to seconds can be useful in various programming scenarios. Here's how you can achieve this conversion:
Without Regular Expressions:
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
Using Regular Expressions:
$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;
These methods allow you to accurately convert time strings to seconds, which can be useful for calculations, comparisons, or other time-related operations in programming.
The above is the detailed content of How to Convert HH:MM:SS or MM:SS Time Strings to Seconds in Programming?. For more information, please follow other related articles on the PHP Chinese website!