时区之间的时间转换

Time conversion between timezones

我有一个适用于 GMT 的服务器应用程序。我的应用程序与柏林时区的服务器通信,我不时从该服务器读取一些文件。我需要比较这些文件的时间。考虑到夏季、冬季时差,如何将远程服务器时间从柏林时区转换为 GMT?你知道 mb boost.date_time 的东西可以帮助我轻松做到吗?

我没有尝试将本地时间转换为格林威治标准时间。我正在从特定时区转换为格林威治标准时间。我需要有一个强大的方法来处理不同的时区。

也许是这个free, open source, C++11/14 timezone library could be of help. You can use it to convert UTC to or from your local timezone, to or from any arbitrary IANA timezone, or between any two arbitrary IANA timezones。该库已移植到 gcc、clang 和 VS。但它需要 <chrono>.

这是一个简短的示例,说明如何获取当前的 UTC 时间,将其转换为柏林当地时间,然后将柏林当地时间转换为您的本地时间,然后将柏林当地时间转换回 UTC。这一切都非常简单,使用现代 C++ 语法和类型安全:

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

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto utc = system_clock::now();
    auto berlin = make_zoned("Europe/Berlin", utc);
    auto local  = make_zoned(current_zone(), berlin);
    auto utc2   = berlin.get_sys_time();
    std::cout << format("%F %T %Z", utc) << '\n';
    std::cout << format("%F %T %Z", berlin) << '\n';
    std::cout << format("%F %T %Z", local) << '\n';
    std::cout << format("%F %T %Z", utc2) << '\n';
}

这只是为我输出:

2016-07-05 01:41:29.207335 UTC
2016-07-05 03:41:29.207335 CEST
2016-07-04 21:41:29.207335 EDT
2016-07-05 01:41:29.207335 UTC

是的,您甚至可以使用 std::chrono::sytem_clock 支持的任何精度转换时区,并解析和格式化该精度。

如果这个库给你带来任何麻烦,你可以在这里获得关于堆栈溢出的帮助,或者chat here, or open an issue here,或者搜索我的电子邮件地址并直接与我联系。

这个库有完整的文档,并且设计为 up-to-date 与最新的 IANA timezone database (even if you need the latest mess the Egyptian politicians have made -- making a timezone rule change with a whole 3 days advance notice). And if your timestamps are antiquated (say from the 1940s), do not worry. This library seamlessly supports the full timezone history that IANA provides. That is, if there is data in the IANA timezone database 保持一致,这个库提取和使用它没有错误。

如果对您的应用程序有帮助,您还可以轻松高效地形成柏林当地的日期文字。例如,您可以在 2016 年 7 月的第一个星期一在柏林指定 15:30(<chrono> 文字需要 C++14):

auto meet = make_zoned("Europe/Berlin", local_days{2016_y/jul/mon[1]} + 15h + 30min);
std::cout << meet << '\n';

输出:

2016-07-04 15:30:00 CEST

如果您想了解纽约办事处必须在什么时间远程办公以参加此会议:

std::cout <<  make_zoned("America/New_York", meet) << '\n';

输出:

2016-07-04 09:30:00 EDT

希望对您有所帮助。