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

江枫思渺然 提交于 2020-01-01 05:50:09

问题


im writing a twitter web service in php. When a user signs in, i receive this node:

<utc_offset>-18000</utc_offset>

I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.

So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset

BTW, this is how i'm getting the server UTC offset value:

$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);

Any ideas? Thanks!


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/5639733/changing-current-user-timezone-based-on-server-utc-offset-and-user-utc-offset

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