【问题标题】:boost date time -- output format提升日期时间——输出格式
【发布时间】:2014-04-28 12:46:37
【问题描述】:

假设我有以下代码:

#include <boost/date_time.hpp>

#include <iostream>
#include <locale>
#include <sstream>

int main()
{
  boost::local_time::local_time_facet* facet = new boost::local_time::local_time_facet("%e %b %Y %T %q");
  std::ostringstream date_osstr;
  date_osstr.imbue(std::locale(date_osstr.getloc(), facet));
  const boost::posix_time::ptime& now = boost::posix_time::second_clock::local_time();
  date_osstr << now;

  std::cout << date_osstr.str() << '\n';
}

我希望输出应该具有以下格式:

2003 年 7 月 1 日 10:52:37 +0200

但输出格式如下:

2014-Apr-28 12:40:04

为什么?我究竟做错了什么?我该如何解决?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    您需要实际使用local_date_time 才能从local_time_facet 中受益:

    #include <boost/date_time.hpp>
    #include <boost/date_time/local_time/local_time.hpp>
    
    #include <iostream>
    #include <locale>
    #include <sstream>
    
    using namespace boost;
    static local_time::time_zone_ptr const utc_time_zone(new local_time::posix_time_zone("GMT"));
    
    int main()
    {
        local_time::local_time_facet* facet = new local_time::local_time_facet("%e %b %Y %T %q");
    
        posix_time::ptime my_ptime = posix_time::second_clock::universal_time();
        local_time::local_date_time now(my_ptime, utc_time_zone);
    
        std::ostringstream date_osstr;
        date_osstr.imbue(std::locale(date_osstr.getloc(), facet));
        date_osstr << now;
    
        std::cout << date_osstr.str() << '\n';
    }
    

    打印

    28 Apr 2014 12:59:01 +0000
    

    Live On Coliru

    【讨论】:

      【解决方案2】:

      您正在使用的构面用于 local_time 对象,但您正在打印 posix_time。相反,使用这个:

      boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%e %b %Y %T %q");
      

      【讨论】:

      • 非常感谢,但现在我的输出中没有 %q 部分
      • 啊,我看到 %q 仅适用于当地时间,在这种情况下,您可能需要 @sehe 的解决方案。同一枚硬币的两面,有点像。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      相关资源
      最近更新 更多