Calculating difference in days using PHP Interval Object?
I've already seen some answers in StackOverflow about how to calculate difference in time between two dates. But no answer are using the DateTime obejct or the Interval Object in PHP. I got the following code snippet from PHP Manual website: http://www.php.net/manual/en/dateinterval.format.php.
<?php
$january = new DateTime('2010-01-开发者_运维问答01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
But the problem is that total days equals 6015 days when it should only be 31 days. I tried to access the instance variable days in the Interval object. It too shows 6015 days. But the instances for month and days intervals are correct. Can someone tell me why?
And I want to use these objects to calculate the difference in times!
Many thanks
UPDATE:
I think it was just a problem with my PHP setup
Running your code...
31 total days
1 month, 0 days
PHP setup issue, perhaps?
I ran that exact same script and got "31 total days" and "1 month, 0 days" (the expected values). Try upgrading your php maybe?..
I'm not sure what version of PHP you're on, but in my experience, I've made it a habit to always set my timezone with date_default_timezone_set('America/Los_Angeles');
where America/Los_Angeles
is the timezone you want to be using. I don't know how this ultimately affects the date calculations, but I do know that PHP 5.3 will yell at you if you try and do date manipulation without specifying a default timezone.
I believe you can also set a default timezone in your php.ini- which I think by default is set to UTC.
精彩评论