Home > Database > Mysql Tutorial > body text

How to Calculate the Sum of Two Time Variables in PHP?

Linda Hamilton
Release: 2024-10-28 05:54:02
Original
687 people have browsed it

How to Calculate the Sum of Two Time Variables in PHP?

PHP: Time Variable Summation

In PHP, determining the combined duration of two distinct time variables can be a perplexing task. However, this can be accomplished with a straightforward solution.

Solution:

To calculate the sum of time variables in PHP, you can take the following steps:

<code class="php">$time1 = '15:20:00'; // First time variable
$time2 = '00:30:00'; // Second time variable

// Convert time variables to timestamps using strtotime()
$timestamp1 = strtotime($time1);
$timestamp2 = strtotime($time2);

// Calculate the sum of timestamps and subtract common seconds
$timestampSum = $timestamp1 + $timestamp2 - strtotime('00:00:00');

// Convert the sum back to time format using date()
$time = date('H:i:s', $timestampSum);

echo $time; // Output: 15:50:00</code>
Copy after login

In this solution, we convert the time variables to timestamps using strtotime(). Then, we calculate the sum of timestamps. However, since timestamps include both hours and seconds, we subtract the number of seconds shared by the two time variables (i.e., 12:00 AM) using strtotime('00:00:00'). Finally, we convert the sum back to a time format using date().

The above is the detailed content of How to Calculate the Sum of Two Time Variables 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!