首页  >  文章  >  数据库  >  如何在 PHP 中计算两个时间变量的总和?

如何在 PHP 中计算两个时间变量的总和?

Linda Hamilton
Linda Hamilton原创
2024-10-28 05:54:02688浏览

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

PHP:时间变量求和

在 PHP 中,确定两个不同时间变量的组合持续时间可能是一项令人困惑的任务。不过,这可以通过简单的解决方案来完成。

解决方案:

要计算 PHP 中时间变量的总和,您可以执行以下步骤:

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

在此解决方案中,我们使用 strtotime() 将时间变量转换为时间戳。然后,我们计算时间戳的总和。但是,由于时间戳包括小时和秒,因此我们使用 strtotime('00:00:00') 减去两个时间变量共享的秒数(即 12:00 AM)。最后,我们使用 date() 将总和转换回时间格式。

以上是如何在 PHP 中计算两个时间变量的总和?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn