diff --git a/lib/Mongo/MongoDate.php b/lib/Mongo/MongoDate.php index 6c1e657a..7571ca84 100644 --- a/lib/Mongo/MongoDate.php +++ b/lib/Mongo/MongoDate.php @@ -88,15 +88,14 @@ public function toBSONType() public function toDateTime() { $datetime = new \DateTime(); + $datetime->setTimezone(new \DateTimeZone("UTC")); $datetime->setTimestamp($this->sec); $microSeconds = $this->truncateMicroSeconds($this->usec); if ($microSeconds > 0) { - $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . str_pad($microSeconds, 6, '0', STR_PAD_LEFT)); + $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u e', $datetime->format('Y-m-d H:i:s') . '.' . str_pad($microSeconds, 6, '0', STR_PAD_LEFT) . ' UTC'); } - $datetime->setTimezone(new \DateTimeZone("UTC")); - return $datetime; } diff --git a/tests/Alcaeus/MongoDbAdapter/Mongo/MongoDateTest.php b/tests/Alcaeus/MongoDbAdapter/Mongo/MongoDateTest.php index 39c3939e..6f75386b 100644 --- a/tests/Alcaeus/MongoDbAdapter/Mongo/MongoDateTest.php +++ b/tests/Alcaeus/MongoDbAdapter/Mongo/MongoDateTest.php @@ -95,4 +95,33 @@ public function testSupportMillisecondsWithLeadingZeroes() $this->assertSame(1234567890, $dateTime->getTimestamp()); $this->assertSame('012000', $dateTime->format('u')); } + + public function testDSTTransitionDoesNotProduceWrongResults() + { + $initialTZ = ini_get("date.timezone"); + + ini_set("date.timezone", "Europe/Madrid"); + + $date = new \MongoDate(1603584000); + $dateTime = $date->toDateTime(); + + $this->assertSame(1603584000, $dateTime->getTimestamp()); + + ini_set("date.timezone", $initialTZ); + } + + public function testDSTTransitionDoesNotProduceWrongResultsWithMicroSeconds() + { + $initialTZ = ini_get("date.timezone"); + + ini_set("date.timezone", "Europe/Madrid"); + + $date = new \MongoDate(1603584000, 123456); + $dateTime = $date->toDateTime(); + + $this->assertSame(1603584000, $dateTime->getTimestamp()); + $this->assertSame('123000', $dateTime->format('u')); + + ini_set("date.timezone", $initialTZ); + } }