2017-04-21 40 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; 
     ... 

}

相关问题