C++ 如何使用boost将日期时间格式化为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5018188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format a datetime to string using boost?
提问by mackenir
I want to format a date/time to a string using boost.
我想使用 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:
并以包含此格式的日期/时间的 wstring 结尾:
%Y%m%d_%H%M%S
Can you show me the code to achieve this? Thanks.
你能告诉我实现这一目标的代码吗?谢谢。
回答by Rob?
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:
我发现这些链接很有用:
回答by Validus Oculus
// 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;