PHP调用timezone_name_from_abbr获取Asia/Dhaka时区返回false如何解决
问题根因
timezone_name_from_abbr() 要求第一个参数传入时区缩写才能正常匹配偏移,空字符串没有对应的时区条目关联,因此无法匹配到偏移21600对应的时区,返回false。
解决方法
方法1:指定时区缩写调用函数
如果你明确需要匹配孟加拉时区,直接传入对应的时区缩写BDT即可:
$timezone = timezone_name_from_abbr("BDT", 21600, false); // 输出结果为 Asia/Dhaka echo $timezone;
方法2:遍历时区列表匹配偏移(适合不知道对应缩写的场景)
如果不确定时区的缩写,直接遍历PHP支持的时区列表,匹配对应偏移即可,还可以按需筛选时区范围:
$targetOffset = 21600; $matchedTimezones = []; // 可根据需要修改筛选范围,例如DateTimeZone::ALL查询全球所有时区 foreach (DateTimeZone::listIdentifiers(DateTimeZone::ASIA) as $tzName) { $tz = new DateTimeZone($tzName); $currentOffset = $tz->getOffset(new DateTime('now', new DateTimeZone('UTC'))); if ($currentOffset === $targetOffset) { $matchedTimezones[] = $tzName; } } // 结果中包含 Asia/Dhaka、Asia/Almaty 等同偏移时区 print_r($matchedTimezones);
内容的提问来源于stack exchange,提问作者Sumon Kaysar
相关产品推荐
相关产品推荐

