Changing current user timezone based on server UTC

2019-03-30 13:48发布

问题:

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.