<?php
/**
* This is an example of datetime handling where dates with different timezones are
* handled in the same application. But of course the server and database are fixed
* to a single matching timezone.
*/
function date_default_timezone_get__example($timezone = null)
{
return $timezone ?: 'UTC';
}
final class DateTimeCorrectTimeZone extends \DateTime {
public static function createFromFormat($format, $time, ?DateTimeZone $object = NULL)
{
$result = parent::createFromFormat($format, $time, $object);
$serverTimeZone = new \DateTimeZone(date_default_timezone_get__example('America/New_York'));
if ($result->getTimeZone() !== $serverTimeZone) {
$result->setTimeZone($serverTimeZone);
}
return $result;
}
}
// UTC Test
$x = DateTimeCorrectTimeZone::createFromFormat('Y-m-d H:i:s', '2001-01-01 12:00:00', new DateTimeZone('UTC'));
print_r($x);
if ($x->format('Y-m-d H:i:s') === '2001-01-01 07:00:00') {
echo "UTC Test Passed\n";
} else {
echo "UTC Test Failed\n";
}
// Same TimeZone Test
$x2 = DateTimeCorrectTimeZone::createFromFormat('Y-m-d H:i:s', '2001-01-01 12:00:00', new DateTimeZone('America/New_York'));
print_r($x2);
if ($x2->format('Y-m-d H:i:s') === '2001-01-01 12:00:00') {
echo "Same Timezone Test Passed\n";
} else {
echo "Same Timezone Test Failed\n";
}
Created
March 22, 2020 03:28
-
-
Save TomHAnderson/b61a2a68bb4e5ec4cf501417e4f63ad7 to your computer and use it in GitHub Desktop.
Auto correcting datetimes with timezones which do not match the server or database
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment