2011-08-18 219 views
4

我有一個boost::posix_time::ptime實例,並希望使用給定的boost::local_time::time_zone_ptr實例將其轉換(「格式」)爲字符串。下面是一個測試程序,顯示我目前有什麼。它將ptime轉換爲local_date_time,據我瞭解,它除了表示時間信息外還表示一個時區。使用自定義時區將boost :: posix_time :: ptime轉換爲字符串

在2011-08-18 12:00:00 UTC運行此程序時,我預計輸出爲2011-08-18 14.00.00 UTC+02:00。相反,它打印2011-08-18 12:00:00 UTC+00:00。即相對於打印時區,打印時間是正確的,但它不在我用來創建實例的時區中。

我目前使用技巧建議in this question來使用自定義格式字符串。

#include <iostream> 
#include <ctime> 

#include <boost/date_time.hpp> 

int main(int argc, char ** argv) { 
    using namespace std; 

    // Get current time, as an example 
    boost::posix_time::ptime dt = boost::posix_time::microsec_clock::universal_time(); 

    // Create a time_zone_ptr for the desired time zone and use it to create a local_date_time 
    boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("EST")); 
    boost::local_time::local_date_time dt_with_zone(dt, zone); 

    std::stringstream strm; 

    // Set the formatting facet on the stringstream and print the local_date_time to it. 
    // Ownership of the boost::local_time::local_time_facet object goes to the created std::locale object. 
    strm.imbue(std::locale(std::cout.getloc(), new boost::local_time::local_time_facet("%Y-%m-%d %H:%M:%S UTC%Q"))); 
    strm << dt_with_zone; 

    // Print the stream's content to the console 
    cout << strm.str() << endl; 

    return 0; 
} 

我應該如何local_date_time實例轉換爲字符串,因此字符串中的日期是由time_zone_ptr實例指定的時區來表示?

+0

你的問題是什麼? –

+0

謝謝,埃米爾,我在最後添加了一個具體問題。 – Feuermurmel

回答

3

我認爲boost並不知道時區說明符。通過

new boost::local_time::posix_time_zone("EST-05:00:00") 

更換

new boost::local_time::posix_time_zone("EST") 
在你的代碼

,一切工作正常。如果要使用通用標準名稱,則必須按照boost文檔中的說明創建時區數據庫。

+0

這正是問題所在!由於構造函數在遇到未知時區規範時沒有拋出異常,因此我並沒有考慮到這種情況。 – Feuermurmel

相關問題