如何使用boost将datetime格式化为string? [英] How to format a datetime to string using boost?

查看:145
本文介绍了如何使用boost将datetime格式化为string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



从当前日期/时间开始:

  ptime now = second_clock :: universal_time(); 

,最后以包含以下格式的日期/时间的wstring:

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

你能告诉我代码来实现吗?谢谢。

解决方案

对于任何值得的,这里是我写的这个功能:

  #includeboost / date_time / posix_time / posix_time.hpp
#include< iostream>
#include< sstream>

std :: wstring FormatTime(boost :: posix_time :: ptime now)
{
使用命名空间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<<<现在;
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

我发现这些链接很有用:




I want to format a date/time to a string using boost.

Starting with the current date/time:

ptime now = second_clock::universal_time();

and ending up with a wstring containing the date/time in this format:

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

Can you show me the code to achieve this? Thanks.

解决方案

For whatever it is worth, here is the function that I wrote to do this:

#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;

}

The output of this program was:

20111130_142732
20111130_142734

I found these links useful:

这篇关于如何使用boost将datetime格式化为string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆