2013-07-23 29 views
0

我使用升壓轉換器的日期對象 我想從這個對象獲得一年字符串或INT獲取一年串

我沒有找到簡單的方法來做到這一點 謝謝! Ron

回答

5
#include <boost/date_time/local_time/local_time.hpp> 
#include <boost/lexical_cast.hpp> 
#include <string> 


std::string x = boost::lexical_cast<std::string> 
        (second_clock::local_time().date().year()); 

應該做的。

+0

非常感謝您! –

0

我爲一個你可能覺得有用的項目編寫了這些函數。在我發現lexical_cast在我的特定代碼中導致性能問題後,我這樣做了。 (無擔保,雖然它運行在我們幾年督促環境罰款;)

using namespace boost; 
    gregorian::date date_from_str(const char* dateStr,const char* format) { 
     int year; 
     int month; 
     int day; 
     sscanf_s(dateStr,format,&year,&month,&day); 
     return gregorian::date(year,month,day); 
    } 
    std::string date_to_str(const gregorian::date& date,const char* format) { 
     char buf[10]; 
     gregorian::date::ymd_type ymd = date.year_month_day(); 
     sprintf_s(buf,sizeof(buf),format,ymd.year,ymd.month,ymd.day); 
     return std::string(buf); 
    } 

    gregorian::date dateInt_to_date(int dateInt) { 
     const int day = dateInt % 100; 
     const int month = (dateInt/100) % 100; 
     const int year = dateInt/10000; 
     return gregorian::date(year,month,day); 
    } 

您可以編輯該只返回年份部分

+0

'sprintf_s'不是非常C++的方式,它甚至只編譯MSVC :) – nothrow

+0

是的!但是對常規C++的轉換很簡單:)我認爲,這對於其他人以及@Ron Gross來說可能是有用的。 – Ronnie

+1

爲什麼downvote?它date_to_str以有效的方式實現你想要的,而其他的則是有幫助的。 – Ronnie