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

如何在可移植C++中获取所有可用时区列表并定位当前时区?

可移植C++枚举所有时区并定位当前时区

核心方案:C++20标准库<chrono>时区支持

C++20引入了标准化的时区处理API,基于IANA时区数据库,是跨平台可移植的首选方案。以下代码可以枚举所有可用时区,并定位当前系统时区的位置:

#include <chrono>
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // 获取全局时区数据库实例
    const auto& tz_db = std::chrono::get_tzdb();

    // 枚举并输出所有时区,同时存入vector用于后续查找
    std::vector<std::string> timezone_list;
    std::cout << "所有可用时区:\n";
    for (const auto& zone_entry : tz_db.zones) {
        const std::string& tz_name = zone_entry.name();
        timezone_list.push_back(tz_name);
        std::cout << tz_name << '\n';
    }

    // 获取当前系统时区
    const auto current_tz = std::chrono::current_zone();
    std::cout << "\n当前系统时区: " << current_tz->name() << '\n';

    // 在枚举列表中查找当前时区的位置
    auto pos = std::find(timezone_list.begin(), timezone_list.end(), current_tz->name());
    if (pos != timezone_list.end()) {
        const size_t index = std::distance(timezone_list.begin(), pos);
        std::cout << "当前时区在列表中的索引位置: " << index << '\n';
    } else {
        std::cout << "当前时区未出现在枚举列表中(理论上不应发生)\n";
    }

    return 0;
}

关键说明

  • 编译要求:必须使用支持C20的编译器,编译时需指定C20标准(例如GCC/Clang用-std=c++20,MSVC用/std:c++20)。
  • 时区数据库:标准库会自动加载系统提供的IANA时区数据库,无需手动配置,保证跨平台一致性。
  • 时区名称格式:枚举的时区名称遵循IANA规范(如America/New_York、Asia/Shanghai),是全球通用的标准格式。

旧版本C++的替代方案(非完全可移植)

如果无法使用C++20,只能依赖平台特定API实现:

  • Linux/macOS:读取/usr/share/zoneinfo目录下的所有时区文件路径,提取时区名称。
  • Windows:使用EnumDynamicTimeZoneInformation API枚举时区,或读取注册表中的时区条目。
    这些方案无法保证跨平台一致性,仅作为临时替代。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:28:09