我的代码应该也可以在linux和windlows上运行。我想获取YYYY-MM-DD HH24:MI:SS中的当前时间。默认时区是UTC+08,因为我的系统可以位于任何时区。
如果你能帮助我编写c++代码(我没有c++11,14编译器),那就太好了。
我看到了一种解决方案-使用time获取UTC的当前时间,然后将TZ环境变量操作到您的目标时区。然后使用localtime_r将其转换为该时区的本地时间。
但是不确定如何使用c++来实现这一点,因为它可以在Windows和linux上工作。
发布于 2017-04-21 16:28:54
我建议研究一下boost库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
发布于 2017-04-22 01:42:35
应该可以在大多数平台上运行:
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;
...}
https://stackoverflow.com/questions/43537549
复制相似问题