首頁  >  文章  >  資料庫  >  當 PHP 中的時間變數跨越多天時,如何計算它們的總和?

當 PHP 中的時間變數跨越多天時,如何計算它們的總和?

Barbara Streisand
Barbara Streisand原創
2024-10-27 15:24:02457瀏覽

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 = "000: 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn