2009-06-30 26 views
1

在C++中什麼是有一天能加入到這個格式的日期的最簡單的方法:升壓日期添加有一天,非標準GMT串

「20090629-05:57:43」

可能使用Boost 1.36 - Boost::dateBoost::posix_date或任何其他boost或std庫功能,我對其他庫不感興趣。

到目前爲止,我想出了:

  • 格式字符串(分割日期和時間部分的字符串操作),以便能夠初始化boost::gregorian::date,日期預計格式,如:

    「2009- 06-29 5點57分43" 秒

    「20090629-05:57:43」

  • 加一天(升壓date_duration東西)

  • 轉換回to_simple_string並追加一部分時間(字符串操作)

是否有任何容易/ niftier方式做到這一點?

我正在尋找運行時效率。

對於上述步驟的示例代碼:

using namespace boost::gregorian; 
string orig("20090629-05:57:43"); 
string dday(orig.substr(0,8)); 
string dtime(orig.substr(8)); 

date d(from_undelimited_string(dday)); 
date_duration dd(1); 
d += dd; 
string result(to_iso_string(d) + dtime); 

結果:

20090630-05:57:43 

回答

1

這是相當接近我所知道的最簡單的方法。關於進一步簡化,將使用方面的I/O的東西,以消除對字符串操作需要的唯一方法:這是更長的時間,而且可能更難理解,雖然

#include <iostream> 
#include <sstream> 
#include <locale> 
#include <boost/date_time.hpp> 

using namespace boost::local_time; 

int main() { 
    std::stringstream ss; 
    local_time_facet* output_facet = new local_time_facet(); 
    local_time_input_facet* input_facet = new local_time_input_facet(); 
    ss.imbue(std::locale(std::locale::classic(), output_facet)); 
    ss.imbue(std::locale(ss.getloc(), input_facet)); 

    local_date_time ldt(not_a_date_time); 

    input_facet->format("%Y%m%d-%H:%M:%S"); 
    ss.str("20090629-05:57:43"); 
    ss >> ldt; 

    output_facet->format("%Y%m%d-%H:%M:%S"); 
    ss.str(std::string()); 
    ss << ldt; 

    std::cout << ss.str() << std::endl; 
} 

。我沒有試圖證明這一點,但我懷疑它會以這種方式實現相同的運行效率。

+0

+1,有趣的解決方案,我會看看。我認爲我可以重新使用格式的方面,然後通過它傳遞日期。 – stefanB 2009-06-30 23:03:45