Home >Backend Development >PHP Tutorial >How to Convert HH:MM:SS (or MM:SS) Time Strings to Total Seconds?

How to Convert HH:MM:SS (or MM:SS) Time Strings to Total Seconds?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 08:25:12414browse

How to Convert HH:MM:SS (or MM:SS) Time Strings to Total Seconds?

Converting Time Strings in HH:MM:SS Format to Seconds

Problem:
How can you convert a time string in the HH:MM:SS format into a flat seconds number? The time string can sometimes be in the format MM:SS only.

Solution:

Method 1: Using Regular Expressions

To convert the time string without splitting it, use the following code:

$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;

Method 2: Using sscanf()

If regular expressions are not preferred, use the following code:

$str_time = "2:50";

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

In the second method, check if the seconds variable is set to handle time strings in the MM:SS format correctly.

The above is the detailed content of How to Convert HH:MM:SS (or MM:SS) Time Strings to Total Seconds?. 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