时差php在字符串上调用成员函数format()

时间:2017-12-28 07:01:24

标签: php html datetime datetime-format

计算以分钟和秒为单位的时差,但发生错误时出现致命错误:在字符串上调用成员函数format()。

 <?php
date_default_timezone_set('Asia/Kolkata');
echo "Time" . date(" h:i:s") . "<br>";
echo "Date " . date("d-m-y") . "<br>";
$now = date("i:s");
echo $now ."<br>";

$nearest = "03:30";
$nearest-> format("%i : %s"); 
echo $nearest  = $nearest->diff($now);
?>

1 个答案:

答案 0 :(得分:2)

日期diff()期望DateTime对象

<?php
    // Set timezone
    date_default_timezone_set('Asia/Kolkata');

    // Current date time
    $now = new DateTime();
    echo "Now: " . $now->format("h:i:s") ."<br>";

    // Date Time to compare
    $nearest = new DateTime("03:30");
    echo "Nearest: ". $nearest->format("h:i:s") ."<br>";

    // Difference between dates
    $difference = $nearest->diff($now);
    echo "Difference: " . $difference->format("%h hours %i minutes %s seconds");
?>