21
我想使用boost將日期/時間格式化爲字符串。如何使用boost將日期時間格式化爲字符串?
與當前的日期/時間開始:
ptime now = second_clock::universal_time();
,幷包含日期/時間在此格式的wstring結束了:
%Y%m%d_%H%M%S
你能告訴我的代碼來實現這一目標?謝謝。
我想使用boost將日期/時間格式化爲字符串。如何使用boost將日期時間格式化爲字符串?
與當前的日期/時間開始:
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;
我現在測試這個 - 可能是wstringstream需要wtime_facet而這也正是它默默地失敗對我來說。 – mackenir 2011-02-16 18:30:19
如果你打算在多個日期使用相同的格式,每次都不創建facet,而是創建一次,然後多次使用它,那麼這樣做會很有效。灌輸本身並不昂貴。 – CashCow 2011-02-24 17:09:38