如何使用 boost 将日期时间格式化为字符串?

26
我想使用boost将日期/时间格式化为字符串。
从当前的日期/时间开始:
ptime now = second_clock::universal_time();

最终得到一个包含日期/时间的wstring,格式如下:

%Y%m%d_%H%M%S

你可以给我展示一下实现这个的代码吗?谢谢。
2个回答

35

不管值不值得,这是我编写的函数:

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

std::wstring FormatTime(boost::posix_time::ptime now)
{
  using namespace boost::posix_time;
  static std::locale loc(std::wcout.getloc(),
                         new wtime_facet(L"%Y%m%d_%H%M%S"));

  std::basic_stringstream<wchar_t> wss;
  wss.imbue(loc);
  wss << now;
  return wss.str();
}

int main() {
  using namespace boost::posix_time;
  ptime now = second_clock::universal_time();

  std::wstring ws(FormatTime(now));
  std::wcout << ws << std::endl;
  sleep(2);
  now = second_clock::universal_time();
  ws = FormatTime(now);
  std::wcout << ws << std::endl;

}
这个程序的输出是:
20111130_142732
20111130_142734

我发现以下链接很有用:


我正在进行测试 - 可能是wstringstream需要一个wtime_facet,这就是它在我的电脑上默默失败的地方。 - mackenir
1
这样做是可行的,但请注意,如果您要为多个日期使用相同的格式,则不要每次都创建facet,而是创建一次并多次使用。imbue本身并不昂贵。 - CashCow
1
请注意,您可以通过存储区域设置对象来实现此操作。 - CashCow
谢谢,@CashCow。我已经按照你的建议进行了更改。 - Robᵩ
对于使用C++98和C++0x,我发现使用std::stringstream更好,因为std::basic_stringstream的模板不同。 - user7851115

3
// create your date
boost::gregorian::date d(2009, 1, 7); 

// create your formatting
boost::gregorian::date_facet *df = new boost::gregorian::date_facet("%Y%m%d_%H%M%S"); 

// set your formatting
ostringstream is;
is.imbue(std::locale(is.getloc(), df));
is << d << endl;

// get string
cout << "output :" << is.str() << endl;

16
伙计们,说真的。在C#中,我可以写DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")就好了!这是C++最近出了什么问题啊… - romanz
5
你听起来像是我高中时的侄子 :) 我确信你提到的函数做的事情与我上面编写的代码非常相似。如果你想要更好的用户界面,那么你需要在 boost 上构建一个抽象层。boost 被设计成具有灵活性。看看 Poco C++ 库。它们拥有非常不错的 Java 风格接口,使编程变得非常容易。所以问题不在于 C++ :) - Validus Oculus
有没有办法将它存储到字符串变量中(即std :: string),而不是直接输出到控制台? - Steve Smith
1
@romanz,当用户定义的格式使用而不是 yyyy-MM-dd HH:mm:ss,并且需要应用特定的时区、语言/区域设置、编码、星期的第一天以及月份/日期缩写时,请尝试使用您的方法。此外,您还需要处理由 DateTime 支持但并不涵盖所有情况的各种格式。 - Aleksey F.
1
@SteveSmith is.str() 返回一个 std::string - ThreeStarProgrammer57

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接