gpt4 book ai didi

c++ - Boost date_time 输出格式被忽略

转载 作者:行者123 更新时间:2023-11-27 23:57:06 26 4
gpt4 key购买 nike

我在尝试找出如何让 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 格式说明符, 然而这被忽略了。

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

最佳答案

我认为您混合了 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();

关于c++ - Boost date_time 输出格式被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41846130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com