Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"DateTime->modify('+0 days')" Modifies DateTime Object

Tags:

php

datetime

Could anyone elaborate on why the following DateTime->modify() code yields those weird contradicting results, depending on the PHP version (is it a bug ? In which PHP version ?).

I would expect all examples to produce the same date and time the objects were created with, but this is apparently not the case.

The only example that seems to work is the one in the middle where the DateTime object is created from a UNIX timestamp and where the time zone is set afterwards (it cannot be set upon construction because that will be ignored).

PHP 5.4.4 and 5.4.6:

FROM TIMESTAMP, NO TZ:
2012-08-21 22:00:00 GMT+0000 (offset 0)  <-- different 
2012-08-21 23:00:00 GMT+0000 (offset 0)  <-- from this
FROM TIMESTAMP, WITH TZ:
2012-08-22 00:00:00 CEST (offset 7200)
2012-08-22 00:00:00 CEST (offset 7200)
FROM STRING:
2012-08-22 00:00:00 CEST (offset 7200)
2012-08-22 00:00:00 CEST (offset 7200)

PHP 5.2.0:

FROM TIMESTAMP, NO TZ:
2012-08-21 22:00:00 GMT+0100 (offset 7200)
2012-08-21 22:00:00 GMT+0100 (offset 7200)
FROM TIMESTAMP, WITH TZ:
2012-08-22 00:00:00 CEST (offset 7200)
2012-08-22 00:00:00 CEST (offset 7200)
FROM STRING:
2012-08-22 00:00:00 CEST (offset 7200)  <-- different
2012-08-21 23:00:00 CEST (offset 7200)  <-- from this

Code:

<?php
  $tz = new DateTimeZone('Europe/Berlin');

  echo "FROM TIMESTAMP, NO TZ:\n";

  $date = new DateTime('@'.strtotime('2012-08-22 00:00:00 CEST'));
  echo $date->format('Y-m-d H:i:s T').' (offset '.$date->getOffset().")\n";

  $date->modify('+0 days');
  echo $date->format('Y-m-d H:i:s T').' (offset '.$date->getOffset().")\n";

  echo "FROM TIMESTAMP, WITH TZ:\n";

  $date = new DateTime('@'.strtotime('2012-08-22 00:00:00 CEST'));
  $date->setTimezone($tz);
  echo $date->format('Y-m-d H:i:s T').' (offset '.$date->getOffset().")\n";

  $date->modify('+0 days');
  echo $date->format('Y-m-d H:i:s T').' (offset '.$date->getOffset().")\n";

  echo "FROM STRING:\n";

  $date = new DateTime('2012-08-22 00:00:00 CEST', $tz);
  echo $date->format('Y-m-d H:i:s T').' (offset '.$date->getOffset().")\n";

  $date->modify('+0 days');
  echo $date->format('Y-m-d H:i:s T').' (offset '.$date->getOffset().")\n";
?>
like image 763
Arc Avatar asked Aug 22 '12 14:08

Arc


1 Answers

Using DateTime::add() and specifying an appropriate DateInterval "P0D" doesn't change the date. I think it's a bug in PHP, please be so kind and report it.

like image 73
Daniel M Avatar answered Oct 08 '22 12:10

Daniel M