Home >Database >Mysql Tutorial >How to Accurately Add Two Time Variables in PHP?
PHP Time Variable Addition
In PHP, it is possible to add two time variables to obtain a cumulative time value. To achieve this, you can use PHP's strtotime() and date() functions.
Example:
Consider the following example:
<code class="php">$time1 = '15:20:00'; $time2 = '00:30:00';</code>
To calculate the sum of these time variables, you can use the following code:
<code class="php">$time = strtotime($time1) + strtotime($time2) - strtotime('00:00:00');</code>
However, this approach may result in incorrect calculations because strtotime() converts time strings to timestamps, which share a common starting point of 00:00:00. This means that if $time1 and $time2 share the same number of seconds, these seconds will be counted twice in the addition.
To work around this issue, we can subtract the shared seconds from the addition using the strtotime('00:00:00') expression:
<code class="php">$time = date('H:i:s', $time); // Convert the timestamp back to a time string</code>
Using this revised code, you will get the correct result of '15:50:00' when adding $time1 and $time2.
The above is the detailed content of How to Accurately Add Two Time Variables in PHP?. For more information, please follow other related articles on the PHP Chinese website!