【发布时间】:2011-06-28 10:32:47
【问题描述】:
我想使用 boost 将日期/时间格式化为字符串。
从当前日期/时间开始:
ptime now = second_clock::universal_time();
并以包含此格式的日期/时间的 wstring 结尾:
%Y%m%d_%H%M%S
你能告诉我实现这一目标的代码吗?谢谢。
【问题讨论】:
标签: c++ formatting datetime
我想使用 boost 将日期/时间格式化为字符串。
从当前日期/时间开始:
ptime now = second_clock::universal_time();
并以包含此格式的日期/时间的 wstring 结尾:
%Y%m%d_%H%M%S
你能告诉我实现这一目标的代码吗?谢谢。
【问题讨论】:
标签: c++ formatting datetime
不管它有什么价值,这里是我为此编写的函数:
#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
我发现这些链接很有用:
【讨论】:
std::stringstream 更好,因为 std::basic_stringstream 的模板不同。
// 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;
【讨论】:
yyyy-MM-dd HH:mm:ss 时尝试使用您的方法,以及特定的时区、语言/区域设置、编码、一周的第一天和月份/天的缩短将被应用。而且你会得到DateTime 支持的地狱格式,它们并不涵盖所有情况。