当 PHP 中的时间变量跨越多天时,如何计算它们的总和?

Barbara Streisand
发布: 2024-10-27 15:24:02
原创
456 人浏览过

How to Calculate the Sum of Time Variables in PHP When They Span Multiple Days?

在 PHP 中计算时间变量的总和

在您的 PHP 应用程序中,您可能会遇到需要对时间变量执行算术运算的情况。让我们探讨一个特定的场景,您想要确定两个时间变量的总和,以“HH:MM:SS”格式的字符串表示。

问题:

如何在 PHP 中添加两个时间变量?

答案:

要在 PHP 中正确求和两个时间变量,我们需要使用以下命令将它们转换为 Unix 时间戳strtotime() 函数。然而,这种转换引入了一个微小的差异。具体来说,strtotime() 函数将时间解释为当天内的时间。因此,当转换属于不同日期的两个时间时,我们需要调整其中一个时间戳以确保总和正确。

解决方案:

  1. 使用 strtotime() 将 $time1 和 $time2 转换为 Unix 时间戳。

    <code class="php">$timestamp1 = strtotime($time1);
    $timestamp2 = strtotime($time2);</code>
    登录后复制
  2. 计算 $time1 和 $time2 共享的秒数之间的差异。这个差异可以通过从较早的时间戳中减去 strtotime('00:00:00')(代表午夜)来计算。

    <code class="php">$seconds_difference = min($timestamp1, $timestamp2) - strtotime('00:00:00');</code>
    登录后复制
  3. 通过减去 $ 来调整较早的时间戳Seconds_difference。

    <code class="php">if ($timestamp1 < $timestamp2) {
       $timestamp1 -= $seconds_difference;
    } else {
       $timestamp2 -= $seconds_difference;
    }</code>
    登录后复制
  4. 将调整后的时间戳相加。

    <code class="php">$timestamp_sum = $timestamp1 + $timestamp2;</code>
    登录后复制
  5. 将时间戳总和转换回“HH:MM:使用 date() 的 SS" 格式。

    <code class="php">$result = date('H:i:s', $timestamp_sum);</code>
    登录后复制

示例:

使用提供的值 $time1 = "15:20: 00" 且 $time2 = "00:30:00",上述解决方案将得到:

<code class="php">$timestamp1 = strtotime('15:20:00'); // 55200
$timestamp2 = strtotime('00:30:00'); // 1800
$seconds_difference = min(55200, 1800) - strtotime('00:00:00'); // 1800
$timestamp1 -= $seconds_difference; // 55200 - 1800 = 53400
$timestamp_sum = $timestamp1 + $timestamp2; // 53400 + 1800 = 55200
$result = date('H:i:s', $timestamp_sum); // "15:50:00"</code>
登录后复制

因此,$time1 和 $time2 之和为“15:50:00”。

以上是当 PHP 中的时间变量跨越多天时,如何计算它们的总和?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!