【问题标题】:Serialize boost ptime with custom format使用自定义格式序列化 boost ptime
【发布时间】:2014-07-05 10:22:48
【问题描述】:

我必须将boost::posix_time::ptime 变量序列化为字符串。我想要的格式是:2014-05-12T16:14:01.809+0200。我无法更改它,因为它是从 Web 服务请求的,我必须遵守请求的格式。 我可以暗示时区是本地时区。 我看到了一些例子,但我没有找到任何能让我从 UTC ptime 获得 std::string 的东西。

添加了一些关于我想要的细节: 我从boost::posix_time::ptime 开始。我想以我之前指定的格式打印它,但我不知道我的实际时区是什么。我必须通过库函数调用找到它。 那么我要做的就是用这个原型写一个函数:std::string time_to_custom_string(boost::posix_time::ptime datetime);

【问题讨论】:

    标签: c++ boost time format posix


    【解决方案1】:

    如果您不介意在000 后面加上小数秒:

    #include <boost/date_time/local_time/local_time.hpp>
    #include <locale>
    
    static boost::local_time::time_zone_ptr const s_timezone(new boost::local_time::posix_time_zone("+02:00"));
    
    std::string mydateformat(boost::local_time::local_date_time const& ldt)
    {
        using namespace boost;
        std::ostringstream 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("%Y-%m-%dT%H:%M:%s%q");
    
        ss.str("");
        ss << ldt;
        return ss.str();
    }
    
    std::string mydateformat()
    {
        using namespace boost;
    
        posix_time::ptime my_ptime = posix_time::second_clock::universal_time();
        local_time::local_date_time ldt(my_ptime, s_timezone);
    
        return mydateformat(ldt);
    }
    
    int main()
    {
        using namespace boost;
    
        gregorian::date d(2014, 5, 12);
        posix_time::time_duration td(16, 14, 1, 809000);
        local_time::local_date_time ldt(d, td, s_timezone, false/*daylight savings*/);
    
        std::cout << mydateformat(ldt) << "\n";
        assert("2014-05-12T16:14:01.809000+0200" == mydateformat(ldt));
    }
    

    【讨论】:

    • 谢谢,这不是我真正想要的,但解释我想要的可能是我的错。它可以帮助我找到真正的解决方案。我用更多细节更新我的问题。
    • @user3807511 从ptime 获取local_date_time 的方法已经显示(在mydateformat 的第二个重载中!)。要使用“系统时区”进行转换,请参阅文档。但是请注意,信任系统时区可能会构成安全漏洞。
    • 你能解释一下为什么utc_time_zone是从包含字符串"+02:00"的表达式初始化的吗?
    • @LightnessRacesinOrbit 啊。没有。明显的疏忽:)
    • 顺便说一句,我发现这个是因为我需要它,而不是因为我在“审核”所以答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多