首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 日期運算類 DateAccount:輕鬆實現日期加減與差值計算

     編輯:PHP 綜合知識

類別功能

DateAccount 提供兩個核心方法:

  • DateAdd($interval, $number, $date):在給定時間戳上加減指定間隔。
  • DateDiff($interval, $date1, $date2):計算兩個時間戳之間的間隔差值。

支援的間隔單位($interval):

單位說明
yyyy年
q季
m月
y / d / w日 / 週
ww週(同 w)
h時
n分
s秒

使用範例

1. 加減運算

$temptime = time();
echo strftime("%Hh%M %A %d %b", $temptime); // 當前時間
$date = new DateAccount();
$temptime = $date->DateAdd("n", 50, $temptime); // 加 50 分鐘
echo "

"; echo strftime("%Hh%M %A %d %b", $temptime); // 結果時間

輸出:

15h41 Saturday 03 Jun
16h31 Saturday 03 Jun

2. 差值計算

$current = time();
$date = new DateAccount();
$new = $date->DateAdd("n", 50, $current);
$diff = $date->DateDiff("n", $current, $new);
echo "Interval between two times: $diff"; // 輸出 50

類別原始碼

<?php
class DateAccount {
    function __construct() {}

    function DateAdd($interval, $number, $date) {
        $dt = getdate($date);
        $hours = $dt["hours"]; $minutes = $dt["minutes"]; $seconds = $dt["seconds"];
        $month = $dt["mon"]; $day = $dt["mday"]; $year = $dt["year"];

        switch ($interval) {
            case "yyyy": $year += $number; break;
            case "q": $month += $number * 3; break;
            case "m": $month += $number; break;
            case "y": case "d": case "w": $day += $number; break;
            case "ww": $day += $number * 7; break;
            case "h": $hours += $number; break;
            case "n": $minutes += $number; break;
            case "s": $seconds += $number; break;
        }
        return mktime($hours, $minutes, $seconds, $month, $day, $year);
    }

    function DateDiff($interval, $date1, $date2) {
        $diff = $date2 - $date1;
        switch ($interval) {
            case "w": return bcdiv($diff, 604800);
            case "d": return bcdiv($diff, 86400);
            case "h": return bcdiv($diff, 3600);
            case "n": return bcdiv($diff, 60);
            case "s": return $diff;
        }
    }
}
?>

注意:bcdiv 需 BCMath 擴展,若環境不支援可改用 floor($diff / 86400) 等整數除法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved