Calculating Time Differences

谁都会走 提交于 2020-01-17 11:15:40

问题


I tried using DateTime in PHP and used diff method to find the time difference between a timestamp and the current time. However PHP gives me the wrong difference. Can anyone point out to me what went wrong in my code? Thanks!

PHP Code

function time() {
    $now = new DateTime;
    $later = new DateTime('2011-10-17 07:08:00');
    $interval = $now->diff($later);
    echo $now->format('y m d');
    echo "<br>";
    echo $later->format('y m d');
    echo "<br>";
    echo $interval->format('%a');
}

Output

11 10 19
11 10 17
6015

The difference is obviously 2 days, but I get 6015 days!


回答1:


You are doing $now->diff($now);, should be $now->diff($later).




回答2:


as written, the result should be 0, because you are doing $now->diff($now)

If you do $later->diff($now) you should get the expected result.



来源:https://stackoverflow.com/questions/7816650/calculating-time-differences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!