【问题标题】:Boost date_time output format being ignoredBoost date_time 输出格式被忽略
【发布时间】:2017-06-10 07:27:51
【问题描述】:

我无法弄清楚如何让 Boost 将日期/时间对象格式化为字符串。我正在尝试设置格式说明符,但它被忽略并继续以预定义的样式输出日期。

通过演示可能更容易解释,所以这里有一些显示问题的示例代码:

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

int main(void)
{
    int i = 1485324852;
    boost::posix_time::ptime pt = boost::posix_time::from_time_t(i);

    boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
    output_facet->format("%d/%m/%Y %H:%M");

    std::stringstream ss;
    ss.imbue(std::locale(std::locale::classic(), output_facet));
    ss << pt;

    std::string strTime = ss.str();
    std::cout << "Time " << i << " converted to UI string: " << strTime << "\n";

    return 0;
}

它给了我这个输出:

Time 1485324852 converted to UI string: 2017-Jan-25 06:14:12

我的预期是:

Time 1485324852 converted to UI string: 25/01/2017 16:14

我已经告诉output_facet 按照example given in the Boost docs 使用%d/%m/%Y %H:%M 格式说明符,但这被忽略了。

我看不出我在设置格式时哪里出错了。这可能是显而易见的,所以有人可以向我指出吗?

【问题讨论】:

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


【解决方案1】:

我认为您正在混合使用 local_dateposix_time

在代码末尾添加可以解决您的问题并打印所需的格式:

boost::local_time::local_date_time ldt(boost::local_time::not_a_date_time);
ss >> ldt;
ss.str("");
ss << ldt;
std::cout << ss.str() << std::endl;

不过,如果您想使用 posix_time 打印所需的格式,您需要更改:

boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();

到:

 boost::posix_time::time_facet *output_facet = new boost::posix_time::time_facet();

【讨论】:

    【解决方案2】:

    好的,我复制了它,我无法使用您的代码获得正确的输出。 这里是sn -p,可以给出正确的输出。我看到的唯一区别是 local_time_facettime_facet

    #include <iostream>
    #include <boost/date_time/posix_time/posix_time.hpp>
    #include <boost/date_time/posix_time/posix_time_io.hpp>
    
    using namespace boost::posix_time;
    using namespace std;
    
    int main(int argc, char **argv) {
      boost::posix_time::ptime now = boost::posix_time::from_time_t(123456789);
      time_facet *facet = new time_facet("%d/%b/%Y %H:%M:%S");
      cout.imbue(locale(cout.getloc(), facet));
      cout <<  now << endl;
    }
    

    【讨论】:

    • 我不确定你的意思 - 我没有使用local_time。如果您对上面的代码进行建议的更改,它会为您编译并生成预期的dd/mm/yyyy 格式吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多