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
Release: 2024-12-11 16:36:15
Original
831 people have browsed it

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);
Copy after login
  • Handle the case where only minutes and seconds are present:
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
Copy after login

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);
Copy after login
  • Then, extract the components and calculate the seconds:
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template