c++ - 跨平台C++ : convert to/from UTC/local time WITH historical tzdata

标签 c++ windows timezone utc

我需要将时间从 UTC 转换为用户选择的时区。我还必须将该时区的用户输入转换为以 UTC 存储。

目前时区以 Olson 格式定义(“美国/洛杉矶”)。

Linux 上使用 timegm 的解决方案很简单,但我找不到在 Windows 上做完全相同事情的跨平台解决方案(或任何解决方案)。

我不能使用 Boost.Date_Time ( http://www.boost.org/doc/libs/1_57_0/doc/html/date_time.html ),因为它不支持历史时区更改,例如多年来不同的 DST 周期。几年前显然有人提交了一个补丁,但似乎没有被接受。

唯一似乎合理的其他解决方案是使用来自:https://www.iana.org/time-zones 的数据和代码。

有没有人试过这个,或者你有更好的主意吗?

最佳答案

Here is a cross platform, open source C++11/C++14 timezone library包装 IANA timezone database ,包括所有历史数据。 IANA 数据库当前维护的 Olson 数据库。

这个库的一个例子是:

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace std::chrono_literals;
    using namespace date;

    auto departure = make_zoned("America/New_York",
                                local_days{dec/30/1978} + 12h + 1min);
    auto flight_length = 14h + 44min;
    auto arrival = make_zoned("Asia/Tehran",
                              departure.get_sys_time() + flight_length);

    std::cout << "departure NYC time:  " << departure << '\n';
    std::cout << "flight time is       " << make_time(flight_length) << '\n';
    std::cout << "arrival Tehran time: " << arrival << '\n';
}

哪些输出:

departure NYC time:  1978-12-30 12:01:00 EST
flight time is       14:44
arrival Tehran time: 1978-12-31 11:45:00 IRST

注意日期:1978 年 12 月。这在历史上是准确的(就时区处理而言)。该论文接着展示了第二天的同一航类如何因德黑兰的时区变化而有不同的到达时间。

上面的例子没有处理闰秒。但是,如果您确实想要处理闰秒,库可以通过少量额外工作来处理它:

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace std::chrono_literals;
    using namespace date;

    auto departure = make_zoned("America/New_York",
                                local_days{dec/31/1978} + 12h + 1min);
    auto departure_utc = to_utc_time(departure.get_sys_time());
    auto flight_length = 14h + 44min;
    auto arrival = make_zoned("Asia/Tehran",
                              to_sys_time(departure_utc + flight_length));

    std::cout << "departure NYC time:  " << departure << '\n';
    std::cout << "flight time is       " << make_time(flight_length) << '\n';
    std::cout << "arrival Tehran time: " << arrival << '\n';
}

departure NYC time:  1978-12-31 12:01:00 EST
flight time is       14:44
arrival Tehran time: 1979-01-01 11:14:59 IRST

这一切都在以下位置进行了详细描述:

http://howardhinnant.github.io/date/tz.html

并免费提供:

https://github.com/HowardHinnant/date

关于c++ - 跨平台C++ : convert to/from UTC/local time WITH historical tzdata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585779/

相关文章:

c++ - 使用 linux 自动工具

c++ - 安全地传递动态对象数组,而无需强制复制

python - 我无法在 Windows 10 的 cmd 中或在 kali linux 的终端中运行 .py 文件

node.js - 时刻和时区转换本地时间失败

C++11 等价于 boost shared_mutex

windows - 使用 OAuth 从 Windows 应用程序访问 Google App Engine 应用程序

python - 在运行时之前安排任务的方法

c++ - 如何获取当前时区?

mysql - 创建DATABASE时的SQL_MODE和TIME_ZONE

C++ 运算符重载奇怪的类型转换