我想使用boost将日期/时间格式化为字符串。
从当前的日期/时间开始:
你可以给我展示一下实现这个的代码吗?谢谢。
从当前的日期/时间开始:
ptime now = second_clock::universal_time();
最终得到一个包含日期/时间的wstring,格式如下:
%Y%m%d_%H%M%S
你可以给我展示一下实现这个的代码吗?谢谢。
ptime now = second_clock::universal_time();
最终得到一个包含日期/时间的wstring,格式如下:
%Y%m%d_%H%M%S
不管值不值得,这是我编写的函数:
#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
我发现以下链接很有用:
// 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
支持但并不涵盖所有情况的各种格式。 - Aleksey F.is.str()
返回一个 std::string
。 - ThreeStarProgrammer57
std::stringstream
更好,因为std::basic_stringstream
的模板不同。 - user7851115