Re: [PHP] Strange Result of Datetime::diff
- Date: Thu, 6 Apr 2017 23:18:04 +0300
- From: Ivan Grigoriev <greedy.ivan@xxxxxxxxx>
- Subject: Re: [PHP] Strange Result of Datetime::diff
03.04.2017 18:44, Christoph M. Becker пишет:
On 03.04.2017 at 15:28, Aziz Saleh wrote:
On Mon, Apr 3, 2017 at 8:39 AM, <naitsirch@xxxxxxxxx> wrote:
I'd expect the following script:
<?php
$date1 = new DateTime('2017-03-01');
$date2 = new DateTime('2017-04-02');
$diff = $date1->diff($date2);
echo "{$diff->m} months and {$diff->d} days.";
?>
would print "1 months and 0 days.". But instead it prints "1 months and 3
days." (see https://3v4l.org/RMuUZ).
What is the reason for this behaviour?
You sure about that, the above should yield 1 months and 1 days since you
have an extra day there:
http://sandbox.onlinephpfunctions.com/code/fe7c7d989101ab5e1dd1530d457bfcc7a1cfa8fa
But see <https://3v4l.org/N5fg7>!
Please, read this: <https://bugs.php.net/bug.php?id=52480>.
DateTime::diff works with UTC timezone. So, it converts current DateTime
object to UTC timezone.
If you want to understand how it calculated, do
$date1->setTimeZone(new DateTimeZone('UTC'));
$date2->setTimeZone(new DateTimeZone('UTC'));
and watch what actual values are used in diff.
One of the ways to calculate difference is to use timezone UTC for
DateTime object
$date1 = new DateTime('2017-03-01', new DateTimeZone('UTC'));
It calculates difference without time shifts and DTS rules.
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php