Skip to content

Instantly share code, notes, and snippets.

@zim32
Created April 27, 2018 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zim32/807c2d409f9b12140159766d9c51cdeb to your computer and use it in GitHub Desktop.
Save zim32/807c2d409f9b12140159766d9c51cdeb to your computer and use it in GitHub Desktop.
Fix PHP datetime time zone.
$wrongDate = new \DateTime('2018-04-25 16:00:00', new \DateTimeZone('+0300'));
// Wed, 25 Apr 2018 16:00:00 +0300
fixZone($wrongDate, new \DateTimeZone('UTC'));
// Wed, 25 Apr 2018 16:00:00 +0000
function fixZone(\DateTime $dateTime, DateTimeZone $rightZone)
{
$offset = $dateTime->getOffset();
$zoneOffset = $rightZone->getOffset($dateTime);
$diff = $zoneOffset - $offset;
if ($diff > 0) {
$dateTime->modify(sprintf('- %d seconds', $diff));
$dateTime->setTimezone($rightZone);
}
if ($diff < 0) {
$diff = abs($diff);
$dateTime->modify(sprintf('%d seconds', $diff));
$dateTime->setTimezone($rightZone);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment