【问题标题】:Output boost::chrono::system_clock::time_point as local time with respect to UTC输出 boost::chrono::system_clock::time_point 作为相对于 UTC 的本地时间
【发布时间】:2015-05-08 17:45:28
【问题描述】:

我正在尝试将 boost::chrono::system_clock::time_point 输出到文件流,以便它显示本地时间,但与 UTC 时间不同,例如:

2015-05-08 11:49:07.890992700 -0400

基于 documentation 应该可以通过使用带有本地时区的 time_fmt 操纵器来实现:

std::ofstream file("MyFile.txt");
boost::chrono::system_clock::time_point timePoint = boost::chrono::system_clock::now();
file << boost::chrono::time_fmt(boost::chrono::timezone::local)
     << timePoint;

但是,我得到的结果是:

2015-05-08 11:49:07.890992700 东部夏令时间

所以基本上,我希望将“东部夏令时间”时区字符串替换为与 UTC 的“-0400”时区差异。我猜结果可能取决于系统本地设置。无论系统设置如何,有没有办法实现这一点?

【问题讨论】:

    标签: c++ boost chrono


    【解决方案1】:

    AFAIK +HHMM 格式被称为 POSIX 时区。

    FWIW 我猜你的意思是system_clock::now(),这里有一些在我的系统上运行的测试:

    $ TZ='Asia/Kathmandu' ./test
    2015-05-10 04:46:40.655817854 +0545
    
    $ TZ='America/Detroit' ./test
    2015-05-09 18:59:57.022323975 -0400
    

    所以它似乎确实取决于平台和潜在的配置(但我认为它不取决于选项的区域设置)。

    也看到它Live On Coliru

    //#include <boost/chrono/chrono_io.hpp>
    #include <boost/chrono/time_point.hpp>
    #include <boost/chrono/io/time_point_io.hpp>
    #include <boost/chrono/chrono.hpp>
    #include <iostream>
    
    int main() {
        boost::chrono::system_clock::time_point timePoint = boost::chrono::system_clock::now();
        std::cout
            << boost::chrono::time_fmt(boost::chrono::timezone::local)
            << timePoint
            << "\n";
    }
    

    [1] 我用tzselect找到了这个:

    The following information has been given:
    
        United States
        Eastern Time - Michigan - most locations
    
    Therefore TZ='America/Detroit' will be used.
    Local time is now:  za mei  9 18:59:38 EDT 2015.
    Universal Time is now:  za mei  9 22:59:38 UTC 2015.
    

    【讨论】:

    • 确实是 system_clock::now() 而不是 system_time::now(),感谢您的注意,我在问题中修正了它。
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多