2012-08-04 66 views
4

我需要能夠在C++中轉換和比較日期。我發現Boost庫非常適合我的需要,但我不能讓它正常工作:比較日期C++(使用boost)

// include headers... 

using namespace boost::posix_time; 
using namespace boost::gregorian; 

ptime p1(second_clock::universal_time()); 

p1 -= weeks(5); // Subtract 5 weeks from p1 using boost... 

std::string old_date("2011-11-19"); // format:YYYY-MM-DD 

std:stringstream ss(old_date); 

ptime p2; 

p2 << ss; 

if(p1 <= p2){ 
    // this should not happen in this case (yet it does!) p1 > p2!! 
} 

基本上我希望能夠減去周(或月)當地日期,然後比較以YYYY-MM-DD格式的字符串形式給出日期...

回答

2

您的區域設置可能未設置爲識別YYYY-MM-DD格式的日期。嘗試設置輸入方面的格式,如Format Strings示例中所示。

以下示範如何設置一個字符串流的輸入和輸出格式爲「ISO擴展」的例子:

#include <iostream> 
#include <boost/date_time/posix_time/posix_time.hpp> 

int main() 
{ 
    using namespace boost::gregorian; 
    using namespace boost::posix_time; 
    using namespace std; 

    stringstream ss; 

    /****** format strings ******/ 
    time_facet* output_facet = new time_facet(); 
    time_input_facet* input_facet = new time_input_facet(); 
    ss.imbue(locale(ss.getloc(), output_facet)); 
    ss.imbue(locale(ss.getloc(), input_facet)); 
    output_facet->format(time_facet::iso_time_format_extended_specifier); 
    input_facet->format(time_input_facet::iso_time_format_extended_specifier); 
    ptime t(second_clock::local_time()); 
    ss << t; 
    cout << ss.str() << endl; // 2012-08-03 23:46:38 
    ss.str("2000-01-31 12:34:56"); 
    ss >> t; 
    assert(t.date().year() == 2000); 
    assert(t.date().month() == 1); 
    assert(t.date().day() == 31); 
    assert(t.time_of_day().hours() == 12); 
    assert(t.time_of_day().minutes() == 34); 
    assert(t.time_of_day().seconds() == 56); 
} 
+0

明白了現在的工作。謝謝您的幫助! – user1432032 2012-08-04 03:41:37