问题
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