Skip to content

Commit

Permalink
Merge branch '1.1.x' into 1.x
Browse files Browse the repository at this point in the history
* 1.1.x:
  Fix wrong handling of timezones when converting UTCDateTime
  • Loading branch information
alcaeus committed Oct 30, 2020
2 parents 3e1d2b0 + cdc54b0 commit cdf0f34
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
5 changes: 2 additions & 3 deletions lib/Mongo/MongoDate.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
29 changes: 29 additions & 0 deletions tests/Alcaeus/MongoDbAdapter/Mongo/MongoDateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit cdf0f34

Please sign in to comment.