2017-04-21 42 views
0

我的代碼也應該在linux &下工作。 我想在YYYY-MM-DD HH24:MI:SS中獲得當前時間。默認時區是UTC + 08,因爲我的系統可以位於任何時區。使用C++獲取特定時區的當前時間

這將是很大的幫助,如果你能幫助我的C++代碼(我沒有C++ 11,14的編譯器)

我看到了一個解決方案 - 用時間來得到當前時間UTC,然後操作TZ環境變量到您的目標時區。然後使用localtime_r轉換爲該時區的本地時間。

但不知道如何用C++來實現這一點,這將適用於Windows和Linux。

+0

我已經使用了較新的[CCTZ(https://github.com/google/cctz)庫這一點。你可以使用它嗎? –

+0

[CCTZ](https://github.com/google/cctz)和[Howard Hinnant的時區庫](https://github.com/HowardHinnant/date)都需要在C++ 11中引入的'' 。但是,是的,這些都可以很容易地完成這項工作(在C++ 11/14/17中)。 –

回答

0

我建議尋找助推庫boost/date_time/posix_time/posix_time.hpp

從那裏,你就可以簡單地得到像目前本地時間,因此:

boost::posix_time::ptime curr_time = boost::posix_time::microsec_clock::local_time(); 

而且它有方法按要求把它變成一個字符串:

std::string curr_time_str = to_simple_string(curr_time); 

而回的ptime對象:

curr_time = boost::posix_time::time_from_string(curr_time_str); 

http://www.boost.org/doc/libs/1_61_0/doc/html/date_time/posix_time.html

+0

我不能使用增強庫.. :(任何其他解決方案將有所幫助 – user2991556

0

應該在大多數平臺上工作:

int main(int argc, const char * argv[]) 
{ 
     time_t ts = 0; 
       struct tm t; 
       char buf[16]; 
       ::localtime_r(&ts, &t); 
       ::strftime(buf, sizeof(buf), "%z", &t); 
       std::cout << "Current timezone: " << buf << std::endl; 
       ::strftime(buf, sizeof(buf), "%Z", &t); 
       std::cout << "Current timezone: " << buf << std::end; 
     ... 

}

相關問題