我有一個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
實例指定的時區來表示?
你的問題是什麼? –
謝謝,埃米爾,我在最後添加了一個具體問題。 – Feuermurmel