写在前面

在写一个脚本的时候,需要用到这部分,就记录了一下

脚本开始时间就在类的构造函数里,结束时间记录在析构函数里

实现

执行结果

执行结果

function getExecTime($etime = 0, $stime = 0)
{     
    // 创建DateTime对象
    $datetime1 = new DateTime();
    $datetime1->setTimestamp($stime);
   
    $datetime2 = new DateTime();
    $datetime2->setTimestamp($etime);
   
    // 计算时间差
    $interval = $datetime1->diff($datetime2);
   
    // 格式化输出
    return $interval->format('%d天 %h小时 %i分钟 %s秒');
}

实际应用示例

/**
 * test
 */
class Test
{
    public $stime;

    function __construct()
    {
        $this -> stime = time();
    }

    public function execMore()
    {
        // 模拟耗时操作
        sleep(20);
    }

    function getExecTime($etime = 0, $stime = 0)
    {
        // 创建DateTime对象
        $datetime1 = new DateTime();
        $datetime1->setTimestamp($stime);

        $datetime2 = new DateTime();
        $datetime2->setTimestamp($etime);

        // 计算时间差
        $interval = $datetime1->diff($datetime2);

        // 格式化输出
        return $interval->format('%d天 %h小时 %i分钟 %s秒');
    }

    function __destruct()
    {
        echo $this -> getExecTime(time()-($this -> stime));
    }
}

$test = new Test();
$test -> execMore();

欢迎关注拓行公众号,分享各种技术博客文章

拓行——奋勇进取,开拓未来,砥砺前行

最后修改:2025 年 06 月 27 日
如果您对各种技术博客文章感兴趣,欢迎关注拓行公众号,分享各种专业技术知识~