Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing timezone of a retrieved date in php

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.

like image 504
Evaldas Raisutis Avatar asked Sep 15 '13 08:09

Evaldas Raisutis


People also ask

How do I convert one time zone to another in PHP?

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') .

What does NOW () return in PHP?

It is a PHP function that "returns the date & time in the same format as the MySQL function NOW()", which is precisely the question.

What timezone is UTC for PHP?

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.


1 Answers

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.

like image 62
Glavić Avatar answered Sep 28 '22 17:09

Glavić