PHP Bug with DateTime diff

After PHP 5.3.0 DateTime::diff was introduced to help with the comparison between two DateTime objects. However it still seems to be a bit buggy. While I was developing a statistics tool and trying to group occurrences by month, I got into a problem with diff functionality between February and March. If you try the following code you can probably reproduce it. (More info and a temporary solution is provided at the 2nd comment)

$first = new DateTime('2011-03-01');
$second = new DateTime('2011-03-29');
$interval = $second->diff($first, true);
echo "{$first->format('Y-M-d')} and {$second->format('Y-M-d')} Difference: {$interval->format('%a')} total day(s), {$interval->format('%D')} day(s), {$interval->format('%M')} month(s), {$interval->format('%Y')} year(s).
";

In Windows 7 with PHP 5.3.5.0, I get:

2011-Mar-01 and 2011-Mar-29 Difference: 6015 total day(s), 00 day(s), 01 month(s), 00 year(s).

In Linux (CentOS) with PHP 5.3.3, I get:

2011-Mar-01 and 2011-Mar-29 Difference: 28 total day(s), 00 day(s), 01 month(s), 00 year(s).

The diff probably thinks that 1st March is 29th of February and that’s the reason behind this issue.

PS. You can also notice another bug at Windows with total days being 6015, this refers to: http://bugs.php.net/bug.php?id=51184

This entry was posted in Bugs, Solutions and tagged , , , , , . Bookmark the permalink.

9 Responses to PHP Bug with DateTime diff

  1. petros says:

    About the windows bug a temporary solution can be found here: http://acme-tech.net/blog/2010/10/12/php-datetimediff-returns-6015/

  2. petros says:

    I investigated the issue a little bit further and it seems to be connected with the timezone. For example if I set my zone to Europe/Stockholm which is +1 GMT then if i set the $first = new DateTime(’2011-03-01 00:59:00′); I still get the wrong result. However an hour value above or equal to +1 ie $first = new DateTime(’2011-03-01 01:00:00′); will give the correct example.

    So if you are GMT + 2 you need to have a value above or equal to 2011-03-01 02:00:00.

    A quick fix is to set your timezone to UTC: date_default_timezone_set(‘UTC’);
    and in this case you match the time with the needed in order to get correct results.

    Another example with the opposite results is to set your timezone to:
    date_default_timezone_set(‘America/Mexico_City’);
    $first = new DateTime(’2011-02-28 22:01:00′);
    $second = new DateTime(’2011-03-29 03:00:00′);
    then the diff will think that you are in the same month. You need to insert a few hours earlier to get correct results.

  3. Corazon says:

    It’s hard to find your page in google. I found it on 20 spot, you should
    build quality backlinks , it will help you to get more visitors.
    I know how to help you, just type in google – k2 seo tips and tricks

  4. Sophie says:

    It’s hard to find your blog in google. I found it on 19
    spot, you should build quality backlinks , it will help you
    to increase traffic. I know how to help you, just search in google – k2 seo tips and tricks

  5. Clarissa says:

    This is certainly good news to the players because it is their
    chance to take advantage of the casino’s ongoing struggle
    to move forward. This episode alone allowed the exchange owners to make a profit of about 78 Bitcoins (about $37,
    000 as of this writing). Bitcoin San Diego meet up was held this past Thursday evening at Downtown Johnny Brown’s sports bar in San Diego.

  6. need to start blog page how and where start it?

  7. Epifania74 says:

    This post is really interesting, but why it is on 18th place in google’s search results.
    It deserves to be in top 5. Many bloggers think that seo is dead in 2016, but it is not true.
    There is sneaky method to reach google’s top 5 that not
    many people know. Just search for: pandatsor’s tools

  8. I needed to get the exact number of days between 2 dates and was relying on the this diff function, but found that I was getting a peculiar result with: ?php $today = new DateTime ( date ( ’2011-11-09′ )); $appt = new DateTime ( date ( ’2011-12-09′ )); $days_until_appt = $appt – diff ( $today )- d ; ? This was returning 0 because it was exactly one month. I had to end up using : ?php $days_until_appt = $appt – diff ( $today )- days ; ? to get 30.

  9. Eugeneneolf says:

    Многие интернет-магазины мебели не работают с производителями напрямую. Это существенно повышает стоимость товаров. Мы же за 10-летний стаж работы сумели наладить сотрудничество с фабриками мебели. Это позволяет нам предлагать своим клиентам действительно качественную продукцию по выгодным ценам. Более того, мы гарантируем, что любой выбранный товар прослужит вам не один год.
    https://md-dm.ru/gostinyye Все это объясняет, почему люди предпочитают именно у нас покупать мебель. Москва – город больших возможностей, так почему бы и вам не подобрать действительно качественную, красивую и гармоничную мебель для своего дома по доступной цене? Большой ассортимент позволит с легкостью найти изделия для интерьеров комнат, выполненных в различных стилях – начиная классикой и заканчивая модерном и эко-стилем.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>