2011-02-16 49 views
21

我想使用boost将日期/时间格式化为字符串。如何使用boost将日期时间格式化为字符串?

与当前的日期/时间开始:

ptime now = second_clock::universal_time(); 

,并包含日期/时间在此格式的wstring结束了:

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

你能告诉我的代码来实现这一目标?谢谢。

回答

25

不管它是值得的,这里是我写这样做的功能:

#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 

我发现有用的这些链接:

+0

我现在测试这个 - 可能是wstringstream需要wtime_facet而这也正是它默默地失败对我来说。 – mackenir 2011-02-16 18:30:19

+1

如果你打算在多个日期使用相同的格式,每次都不创建facet,而是创建一次,然后多次使用它,那么这样做会很有效。灌输本身并不昂贵。 – CashCow 2011-02-24 17:09:38

2
// 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; 
相关问题