【问题标题】:Boost - Formatting sub second precision time with a time stampBoost - 使用时间戳格式化亚秒精度时间
【发布时间】:2011-09-28 20:25:50
【问题描述】:

我需要以毫秒精度获得格式良好的时间戳(稍作修改的 ISO 8601)。

示例日期如下所示:2011-09-28 13:11:15.237-08:00
格式也应该能够被覆盖。

我一直在玩 boost::posix_time::microsec_clock::local_time()boost::posix_time::time_facet,除了时间戳之外,它们都很好用。
由于 posix 时间不包含时区信息,这是不可能的(我猜)

那么,还有什么我可以使用的具有毫秒精度的包含时区信息的东西,或者我可以让time_facet 与时区一起工作吗?

也许我应该始终使用 UTC?

谢谢

【问题讨论】:

    标签: c++ boost boost-date-time


    【解决方案1】:

    看看 boost::local_time::local_date_time 类。您可以指定一个时区并使用本地微秒时钟来初始化它,就像

    boost::local_time::local_date_time  my_ldt(boost::local_time::local_microsec_clock::local_time(new boost::local_time::posix_time_zone("EST-5EDT,M4.1.0,M10.5.0")));
    

    然后您应该能够使用构面格式化为字符串。

    编辑:完整示例:

    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <sstream>
    
    #include <boost/date_time/local_time/local_time.hpp>
    
    int main(void)
    {
        boost::posix_time::ptime  now = boost::posix_time::second_clock::local_time();
        boost::posix_time::ptime  utc = boost::posix_time::second_clock::universal_time();
    
        boost::posix_time::time_duration tz_offset = (now - utc);
    
        std::stringstream   ss;
        boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
        ss.imbue(std::locale(std::locale::classic(), output_facet));
    
        output_facet->format("%H:%M:%S");
        ss.str("");
        ss << tz_offset;
    
        boost::local_time::time_zone_ptr    zone(new boost::local_time::posix_time_zone(ss.str().c_str()));
        boost::local_time::local_date_time  ldt = boost::local_time::local_microsec_clock::local_time(zone);
        boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
        ss.imbue(std::locale(std::locale::classic(), output_facet));
        output_facet->format("%Y-%m-%d %H:%M:%S%f%Q");
        ss.str("");
        ss << ldt;
        std::cout << ss.str() << std::endl; // "2004-02-29 12:34:56.000789-05:00"
    
        std::cout << "Press return to exit" << std::endl;
        std::string wait_for_line;
        std::getline(std::cin, wait_for_line);
    
        return (0);
    }
    

    【讨论】:

    • 但我不想自己指定时区,我希望它是系统时区
    • @Nicklas A:对不起,错过了。查看这个问题 (stackoverflow.com/questions/2136970/…),您需要执行一些特定于操作系统的调用以获取当前时区,然后嵌入到 Boost 自定义时区中。
    • 我想知道获取通用时间和本地时间并进行比较会有多有效。
    • @Nicklas A:我已经更新了我的代码以表明它是可能的,尽管你只获得了当前的偏移量而不是完整的时区规范。
    • 不错的简单解决方案。我只是用一个循环改进了你的代码,以避免现在和 UTC 之间有 1 秒的差异,从而产生像 UTC+01:59:59 之类的偏差
    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2023-03-17
    • 2014-03-20
    相关资源
    最近更新 更多