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
Release: 2024-12-08 07:14:11
Original
609 people have browsed it

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);
    Copy after login
  2. Extract hours, minutes, and seconds using sscanf:

    sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
    Copy after login
  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;
Copy after login

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;
Copy after login

Example Usage:

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

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!

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