0

Can someone explain me this 'logic'?

$datetime1 = date_create('2012-04-01');
$datetime2 = date_create('2012-05-01');
$interval = date_diff($datetime1, $datetime2);
print_r($interval);

returning 0m (months) and 30d (days). But:

$datetime1 = date_create('2012-05-01');
$datetime2 = date_create('2012-06-01');
$interval = date_diff($datetime1, $datetime2);
print_r($interval);

returns 1m (months) and 1d (days).

(PHP 5.3.15, LC_ALL en_US)

UPDATE

I use php_value date.timezone Europe/Amsterdam which seems to make the difference. Still think it's weird, eastern time or not, it should just give 1 month. Right?

http://sandbox.onlinephpfunctions.com/code/f28914a13f4047c79a19bae70570029a39196148

animuson
  • 53,861
  • 28
  • 137
  • 147
Sanne
  • 1,116
  • 11
  • 17
  • I get: DateInterval Object ( [y] => 0 [m] => 1 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 30 ) - DateInterval Object ( [y] => 0 [m] => 1 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 31 ) [php 5.3.13] – Brett Gregson Dec 04 '12 at 21:11
  • I think we need Jon Skeet :) – Brett Gregson Dec 04 '12 at 21:15
  • My guess: May (month 5) has 31 days, so it's 31 days from May 1st to June 1st. PHP assumes 1 month = 30 days, hence 31 days = 1 month, 1 day. – Mr. Llama Dec 04 '12 at 21:18
  • http://sandbox.onlinephpfunctions.com/code/421022bbbadf209737be3666c111bd5fece63df9 Php 5.3.15 all one month and one day. I guess it has something to do with your platform. All php versions give the same result – Green Black Dec 04 '12 at 21:27

1 Answers1

0

From the PHP docs:

The DateInterval::format() method does not recalculate carry over points in
time strings nor in date segments. This is expected because it is not possible
to overflow values like"32 days" which could be interpreted as anything from
"1 month and 4 days" to "1 month and 1 day".

http://php.net/manual/en/dateinterval.format.php

Although I do find it strange that different versions of PHP do handle it that differently

Brett Gregson
  • 5,867
  • 3
  • 42
  • 60
  • I think this isn't the reason. I figured out that TimeZone has influence. – Sanne Dec 05 '12 at 12:07
  • Might be a combination of both, very strange behavior! Put what you found in an answer for anyone in the future having the same problem – Brett Gregson Dec 05 '12 at 12:36