You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于国家和地区ISO代码获取对应时间(兼容PHP7.3)

基于国家/地区ISO代码获取对应区域时间的PHP兼容方案

核心实现思路

PHP 7.3及以上版本无需依赖已废弃的geoip扩展,可直接通过内置的DateTime、DateTimeZone系列方法实现需求:IANA时区数据库内置了国家、地区代码与时区的映射关系,PHP官方会同步更新该数据库,无需手动维护映射规则。

可直接使用的实现代码

function getTimezoneByCountryAndRegion(string $countryCode, ?string $regionCode = null): ?DateTimeZone
{
    // 过滤指定国家的所有合法时区,国家代码统一转为大写
    $countryTimezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, strtoupper($countryCode));
    if (empty($countryTimezones)) {
        return null;
    }

    // 未传入地区代码时直接返回该国默认第一个时区
    if (empty($regionCode)) {
        return new DateTimeZone($countryTimezones[0]);
    }

    $regionCode = strtoupper($regionCode);
    foreach ($countryTimezones as $timezoneName) {
        $tz = new DateTimeZone($timezoneName);
        $location = $tz->getLocation();
        // 匹配对应地区的ISO代码
        if (strtoupper($location['region_code'] ?? '') === $regionCode) {
            return $tz;
        }
    }

    // 未匹配到对应地区时返回该国时区作为降级方案
    return new DateTimeZone($countryTimezones[0]);
}

使用示例

// 获取澳大利亚昆士兰州(AU + QLD)当前时间
$auQldTimezone = getTimezoneByCountryAndRegion('AU', 'QLD');
$auQldNow = new DateTime('now', $auQldTimezone);
echo $auQldNow->format('Y-m-d H:i:s');

// 获取美国阿拉斯加州(US + AK)当前时间
$usAkTimezone = getTimezoneByCountryAndRegion('US', 'AK');
$usAkNow = new DateTime('now', $usAkTimezone);
echo $usAkNow->format('Y-m-d H:i:s');

方案优势

  • 兼容性强:仅依赖PHP内置的日期扩展,PHP 5.3以上版本均支持,完美适配PHP 7.3及所有后续版本,无需安装额外PECL扩展
  • 准确性高:直接复用PHP官方维护的IANA时区数据库,无需手动更新时区映射规则
  • fallback机制完善:未匹配到对应地区时区时自动返回对应国家的默认时区,避免报错

注意:如果对应国家地区存在多个时区,可根据业务需求在匹配到的时区列表中自行选择目标时区,上述代码默认返回第一个匹配到的时区。

内容的提问来源于stack exchange,提问作者Artoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:24:01