【问题标题】:Use boost or std to get the current local time in a specific timezone使用 boost 或 std 获取特定时区的当前本地时间
【发布时间】:2017-11-29 08:22:48
【问题描述】:

是否可以使用 Boost 库或 std 在不知道偏移量但只知道 TZ 的情况下获取特定时区的当前时间?

例如:“欧洲/罗马”的当前当地时间是多少?

【问题讨论】:

    标签: c++ c++11 boost


    【解决方案1】:

    这是与Howard Hinnant's free, open-source, cross-platform, C++11/14 timezone library 的单行代码:

    #include "date/tz.h"
    #include <iostream>
    
    int
    main()
    {
        std::cout << date::make_zoned("Europe/Rome", std::chrono::system_clock::now()) << '\n';
    }
    

    这只是为我输出:

    2017-11-29 16:24:32.710766 CET
    

    【讨论】:

    • 我希望避免任何额外的库,但这个库比其他库更简单。很可能,我会选择这个库。
    • 如果它有帮助,这个库被提议用于未来的 C++ 标准。它可能不会成功,但目前的赔率是 60/40。在&lt;chrono&gt;(最好是 2020 年)中看到它还需要几年的时间。但我正在努力……
    • 这是一个我可以在我的 CMake 项目中使用的头文件吗?
    • 不,时区支持需要一些安装:howardhinnant.github.io/date/tz.html#Installation 有一个源文件,可以选择使用操作系统的时区数据库,或者直接从 IANA 网站下载一个手动或自动。该项目目前正在开发 CMake 支持。
    【解决方案2】:

    检查这个:https://theboostcpplibraries.com/boost.datetime-location-dependent-times

    #include <boost/date_time/local_time/local_time.hpp>
    #include <iostream>
    
    using namespace boost::local_time;
    using namespace boost::posix_time;
    using namespace boost::gregorian;
    
    int main()
    {
        time_zone_ptr tz{new posix_time_zone{"CET+1"}};
        ptime pt{date{2014, 5, 12}, time_duration{12, 0, 0}};
        local_date_time dt{pt, tz};
        std::cout << dt.utc_time() << '\n';
        std::cout << dt << '\n';
        std::cout << dt.local_time() << '\n';
        std::cout << dt.zone_name() << '\n';
    }
    

    输出:

    2014-May-12 12:00:00 
    2014-May-12 13:00:00 CET 
    2014-May-12 13:00:00 
    CET
    

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 1970-01-01
      • 2012-03-23
      • 2012-09-13
      • 1970-01-01
      • 2019-06-14
      • 2017-04-30
      • 2015-08-24
      • 2020-05-27
      相关资源
      最近更新 更多