boost :: posix_time :: time_facet和boost :: posix_time :: time_input_facet

时间:2019-04-30 10:25:41

标签: c++ boost

我正在尝试将boost::posix_time::ptime转换为特定的字符串格式(扩展的ISO),然后再转换回boost::posix_time::ptime

令人惊讶的是,看起来boost::posix_time::time_facet %f的意思是000000999999(没有小数点分隔符)。但是对于boost::posix_time::time_input_facet,这意味着.000000.999999(带小数点分隔符)。

请参阅:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

int main( int argc, char** argv )
{
    auto now = boost::posix_time::second_clock::local_time();

    std::stringstream outStr;
    {
        boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
        facet->format("%Y-%m-%dT%H:%M:%S.%f");
        outStr.imbue(std::locale(std::locale::classic(), facet));
        outStr << now;
    }
    std::cout << outStr.str() << std::endl;

    {
        static const std::string format = "%Y-%m-%dT%H:%M:%S.%f";
        const std::locale loc = std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(format));
        std::istringstream is(outStr.str());
        is.imbue(loc);
        boost::posix_time::ptime converted;
        is >> converted;
        std::cout << converted << std::endl;
    }

    {
        static const std::string format = "%Y-%m-%dT%H:%M:%S%f";
        const std::locale loc = std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(format));
        std::istringstream is(outStr.str());
        is.imbue(loc);
        boost::posix_time::ptime converted;
        is >> converted;
        std::cout << converted << std::endl;
    }

    return 0;
}

This outputs

2019-04-30T12:23:29.000000
not-a-date-time
2019-Apr-30 12:23:29

虽然我期望:

2019-04-30T12:23:29.000000
2019-Apr-30 12:23:29
not-a-date-time

我正在使用Boost 1.68。

我是在做错什么还是boost::posix_time::time_facetboost::posix_time::input_time_facet中的错误?

注意:“%F”没有此问题。

1 个答案:

答案 0 :(得分:0)

这绝对是一个增强错误。我在这里填写问题: https://github.com/boostorg/date_time/issues/102

使用%F效果更好,但是如果时间没有小数信息,则行为会有所不同: Try this