问题
Can anybody explain me following behaviours:
$end = new DateTime("2015-03-01", new DateTimeZone("Europe/Berlin"));
$start = new DateTime("2015-02-01", new DateTimeZone("Europe/Berlin"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 0 [d] => 28 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 28 )
If I don't use a timezone or Europe/Berlin I get wrong time diffs. 28 days is indeed correct, but in this case it's a month.
$end = new DateTime("2015-03-01", new DateTimeZone("UTC"));
$start = new DateTime("2015-02-01", new DateTimeZone("UTC"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 1 [d] => 0 [h] => 0 [i] =>; 0 [s] => 0 [invert] => 0 [days] => 28 )
with UTC it works
$end = new DateTime("2015-04-01", new DateTimeZone("Europe/Berlin"));
$start = new DateTime("2015-03-01", new DateTimeZone("Europe/Berlin"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 1 [d] => 3 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 31 )
1 month and 3 days?!? February, are you spooking here?
$end = new DateTime("2015-04-01", new DateTimeZone("UTC"));
$start = new DateTime("2015-03-01", new DateTimeZone("UTC"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 1 [d] => 0 [h] => 0 [i] =>; 0 [s] => 0 [invert] => 0 [days] => 31 )
31 days = 1 month, UTC is correct
$end = new DateTime("2015-05-01", new DateTimeZone("Europe/Berlin"));
$start = new DateTime("2015-04-01", new DateTimeZone("Europe/Berlin"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 0 [d] => 30 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 30 )
30 days are for Europe not a month as well?
$end = new DateTime("2015-05-01", new DateTimeZone("UTC"));
$start = new DateTime("2015-04-01", new DateTimeZone("UTC"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 1 [d] => 0 [h] => 0 [i] =>; 0 [s] => 0 [invert] => 0 [days] => 30 )
UTC correct
$end = new DateTime("2015-06-01", new DateTimeZone("Europe/Berlin"));
$start = new DateTime("2015-05-01", new DateTimeZone("Europe/Berlin"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 1 [d] => 1 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 31 )
again 31 days, correct one month, but why +1 day?
$end = new DateTime("2015-06-01", new DateTimeZone("UTC"));
$start = new DateTime("2015-05-01", new DateTimeZone("UTC"));
$diff = $start->diff($end);
//result: DateInterval Object ( [y] => 0 [m] => 1 [d] => 0 [h] => 0 [i] =>; 0 [s] => 0 [invert] => 0 [days] => 31 )
UTC still correct
I don't get it. Thanks for your help.
回答1:
I believe you are experiencing a known bug.
See:
- PHP::Bug #52480 Incorrect difference using DateInterval
来源:https://stackoverflow.com/questions/30592498/php-datetime-timedifference-only-correct-in-utc-timezone