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

How to Convert HH:MM:SS Time to Total Seconds in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 07:14:11610browse

How to Convert HH:MM:SS Time to Total Seconds in PHP?

Converting Time in HH:MM:SS Format to Seconds

Converting time in HH:MM:SS format to a flat seconds number is a common task in programming. This can be achieved using a straightforward procedure.

Solution:

There are two approaches to this conversion:

Approach 1: Using Regular Expressions

  1. Add leading zeros to the MM:SS format if it exists. This can be done using regular expressions:

    $str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00::", $str_time);
  2. Extract hours, minutes, and seconds using sscanf:

    sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
  3. Calculate seconds by multiplying hours by 3600, minutes by 60, and adding the seconds.

Approach 2: Without Regular Expressions

For time in MM:SS format, use the following:

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;

For time in HH:MM:SS format, directly extract hours, minutes, and seconds using sscanf:

sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;

Example Usage:

$str_time = "23:12:95";
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
echo $time_seconds; // Output: 83575

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