Mehmet
Mehmet

Reputation: 3347

PHP time localisation server to region

On my server database I have a datetime attribute with server time and my data is like this:

2015-08-05 18:50:00

On my compter time is:

2015-08-05 21:50:00

How can I convert the server time from server database to local time per different users for different regions? For example, I need to add 3 hours for my computer.

Upvotes: 0

Views: 42

Answers (1)

John Conde
John Conde

Reputation: 219834

You need to account for timezones. DateTime() and DateTimeZone() make this easy.

$datetime = new DateTime(); // now in server time zone
echo $datetime->format('Y-m-d H:i:s');
$datetime->setTimezone(new DateTimeZone('America/New_York')); // change TZ to New York (ET)
echo $datetime->format('Y-m-d H:i:s');

You just need to change the timezone to be the one that applies to your scenario. There is a list of timezones to choose from.

If you want to be sure the starting timezone is consistent just in case your server timezone changes you can explicitly declare that, too.

$datetime = new DateTime(null, new DateTimeZone('America/Los_Angeles')); 
echo $datetime->format('Y-m-d H:i:s');
$datetime->setTimezone(new DateTimeZone('America/New_York')); 
echo $datetime->format('Y-m-d H:i:s');

Demo

Upvotes: 1

Related Questions