Home >Backend Development >PHP Tutorial >How to Convert HH:MM:SS or MM:SS Time Strings to Seconds in Programming?

How to Convert HH:MM:SS or MM:SS Time Strings to Seconds in Programming?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 16:36:15834browse

How to Convert HH:MM:SS or MM:SS Time Strings to Seconds in Programming?

Converting Time Strings (HH:MM:SS or MM:SS) to Seconds Only

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:

  • Split the time string into its components (hours, minutes, and seconds) using sscanf, assuming a fixed format:
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
  • Handle the case where only minutes and seconds are present:
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

Using Regular Expressions:

  • Modify the time string to a standardized format (00:HH:MM):
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00::", $str_time);
  • Then, extract the components and calculate the seconds:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn