gpt4 book ai didi

php - Codeigniter、timezone_menu 和 date_default_timezone_set

转载 作者:可可西里 更新时间:2023-11-01 12:51:54 24 4
gpt4 key购买 nike

我使用 Codeigniters timezone_menu 给出 drop down box时区,我想知道我们应该如何通过 PHP date_default_timezone_set 使用这些时区?

codeigniters 时区的一个例子是 UP1。但是,您不能将其与 PHP date_default_timezone_set 一起使用,因为它接收的字符串应该类似于 Europe/Berlin

问题是,有没有办法将 codeigniter 时区字符串转换为 date_default_timezone_set 可以接受的 PHP 时区字符串?

最佳答案

以下对我有用:

// 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;
}

编辑原始函数不排除 DST 偏移量。 timezone_abbreviations_list() 列出了 DST 标记为 true 的时区的 2x,例如塔斯马尼亚出现在 +11 和 +10 之下。因此,如果 DST == TRUE,则忽略它作为返回列表的一部分。

//-- 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
}

一些例子:

//-- 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

关于php - Codeigniter、timezone_menu 和 date_default_timezone_set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5212620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com