I am retrieving a date in format of 2013-09-15 08:45:00 from the database, which is set in UTC and I need to change it to another dynamic timezone (based on user)
So far I've got
$datetime = $row->field_data_field_performance_times_field_performance_times_v;
$eventDate = DateTime::createFromFormat('Y-m-d H:i:s', $datetime, new DateTimeZone($user->timezone));
$performance_time = date_format($eventDate, 'l, j F, Y, H:i');
But it doesn't change the timezone. Any ideas what's wrong? It should be +2 hours in my case.
php $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru')); echo $date->format('Y-m-d H:i:sP') . "\n"; $date->setTimezone(new DateTimeZone('Pacific/Chatham')); echo $date->format('Y-m-d H:i:sP') .
It is a PHP function that "returns the date & time in the same format as the MySQL function NOW()", which is precisely the question.
The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts. See PHP's list of supported timezones to find the names of all possible timezones you can use for the date.
Your input datetime is in UTC, not user's timezone. So first you must create datetime object in UTC, and then set/change timezone to user's :
$dt = new DateTime('2013-09-15 08:45:00', new DateTimeZone('UTC'));
print_r($dt);
/*
DateTime Object
(
[date] => 2013-09-15 08:45:00
[timezone_type] => 3
[timezone] => UTC
)
*/
Now you have datetime in UTC timezone. If you wish to change timezone, just call ->setTimezone()
on DateTime object :
$dt->setTimezone(new DateTimeZone('Europe/Berlin'));
print_r($dt);
/*
DateTime Object
(
[date] => 2013-09-15 10:45:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)
*/
p.s. because input 2013-09-15 08:45:00
is in standard datetime format, you don't need to use DateTime::createFromFormat
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With