Created
April 27, 2018 13:27
-
-
Save zim32/807c2d409f9b12140159766d9c51cdeb to your computer and use it in GitHub Desktop.
Fix PHP datetime time zone.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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