The following works for me:
// Example - timezones is part of the date helper function
// You obviously wouldn't echo it out, you would pass it in to
// set default timezone function in PHP based on the posted data from
// the dropdown
echo timezone_by_offset(timezones('UM5')); // ouputs 'America/Porto_Acre' which is (-5)
// And the function
function timezone_by_offset($offset) {
$offset = ($offset+1) * 60 * 60;
$abbrarray = timezone_abbreviations_list();
foreach ($abbrarray as $abbr) {
foreach ($abbr as $city) {
if ($city['offset'] == $offset) {
echo($city['timezone_id']);
return true;
}
}
}
echo "UTC";
return false;
}
EDIT
The original function didn't exclude DST offsets. timezone_abbreviations_list() lists 2x for a timezone that has DST marked as true, for example Tasmania appears under +11 and +10. So if DST == TRUE, ignore it as part of the return listing.
//-- Function -------------------------------------------------------------------
function timezone_by_offset($offset) {
$abbrarray = timezone_abbreviations_list();
$offset = $offset * 60 * 60;
foreach ($abbrarray as $abbr) {
foreach ($abbr as $city) {
if ($city['offset'] == $offset && $city['dst'] == FALSE) {
return $city['timezone_id'];
}
}
}
return 'UTC'; // any default value you wish
}
Some examples:
//-- Test Cases -------------------------------------------------------------------
echo timezone_by_offset(-12) . '<br/>';
echo (date_default_timezone_set(timezone_by_offset(-12)) == TRUE ? 'Valid' : 'Not Valid'). '<br/>';
// Etc/GMT+12
// Valid
echo timezone_by_offset(-10) . '<br/>';
echo (date_default_timezone_set(timezone_by_offset(-10)) == TRUE ? 'Valid' : 'Not Valid'). '<br/>';
// America/Anchorage
// Valid
echo timezone_by_offset(-8) . '<br/>';
echo (date_default_timezone_set(timezone_by_offset(-8)) == TRUE ? 'Valid' : 'Not Valid'). '<br/>';
// Etc/GMT+8
// Valid
echo timezone_by_offset(6) . '<br/>';
echo (date_default_timezone_set(timezone_by_offset(6)) == TRUE ? 'Valid' : 'Not Valid'). '<br/>';
// Asia/Aqtobe
// Valid
echo timezone_by_offset(7) . '<br/>';
echo (date_default_timezone_set(timezone_by_offset(7)) == TRUE ? 'Valid' : 'Not Valid'). '<br/>';
// Indian/Christmas
// Valid
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…