Changing current user timezone based on server UTC offset and user UTC offset

谁都会走 提交于 2019-12-03 16:48:07

To get current server time

date_default_timezone_set(date_default_timezone_get());
echo date('Y-m-d H:i:s', time());

Output for Europe/Paris (my server settings; UTC+2)

2011-04-12 20:39:43

To get user's time by offset

$user_offset = '-18000';
date_default_timezone_set('UTC');
$diff = "$user_offset seconds";
if ((substr($diff,0,1) != '+') && (substr($diff,0,1) != '-')) $diff = '+' . $diff;
$usertime = strtotime($diff, time());
echo date('Y-m-d H:i:s', $usertime);

Output UTC-5 (Ecuador -> Quito time NO DST), php timezone identifier 'America/Guayaquil'.

2011-04-12 13:39:43

PHP.net manual:

Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. (-43200 through 50400)

The date_default_timezone... functions expect a string giving something like "Africa/Luanda" or whatever.

I suggest programmatically searching through the timezone database for a matching offset. If I recall correctly, those are in minutes from UTC, so you should divide the offset you are given by 60.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!