使用C 在特定时区获取当前时间

get current time in specific timezone using c++

本文关键字:时间 获取 定时区 使用      更新时间:2023-10-16

我的代码应在linux&还有风力。我想在Yyyy-MM-DD HH24:MI:SS中获得当前时间。默认时区为UTC 08,其中我的系统可以位于任何时区。

如果您可以帮助我使用C 代码(我没有C 11,14编译器(

我看到了一种解决方案 - 利用时间在UTC中获得当前时间,然后操纵目标时区的TZ环境变量。然后使用localtime_r转换为时区的本地时间。

,但不确定如何使用适用于Windows和Linux的C 实现此目标。

我建议您查看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/posix_time.html

应该在大多数平台上工作:

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;
        ...

}