boost日期时间--输出格式

boost date time -- output format

本文关键字:输出 格式 时间 日期 boost      更新时间:2023-10-16

假设我有以下代码:

#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年4月28日12:40:04

为什么?我做错了什么?我该怎么修?

您需要实际使用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

查看Coliru直播

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

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