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

我想使用 boost 将日期/时间格式化为字符串。

从当前日期/时间开始:

ptime now = second_clock::universal_time();

并以包含此格式的日期/时间的 wstring 结尾:

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

你能告诉我实现这一目标的代码吗?谢谢。

最佳答案

不管它有什么值(value),这里是我为此编写的函数:

#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

我发现这些链接很有用:

  • How to format date time object with format dd/mm/yyyy?
  • http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.time_facet
  • http://www.cplusplus.com/reference/iostream/stringstream/str/

https://stackoverflow.com/questions/5018188/

相关文章:

c# - 如何避免浪费屏幕空间编写稀疏的 C# 代码?

.net - 格式化负 TimeSpan

powershell - 在字符串中格式化 PowerShell Get-Date

php - 去除字符串中的非数字字符

android - 使用电话号码格式 NaN 屏蔽 EditText,如 PhoneNumberUt

android - 获取 Google Play 商店应用 HTML 动态徽章

c# - 扩展内置类型的自定义格式功能

c# - 在 Console.WriteLine 方法中格式化字符串

javascript - Chart.js 数字格式

python - 如何使用 Python 的 optparse 格式化位置参数帮助?