【问题标题】:get current time in specific timezone using c++使用 C++ 获取特定时区的当前时间
【发布时间】:2017-09-18 03:38:28
【问题描述】:

我的代码也应该在 linux 和windlows 上运行。 我想在 YYYY-MM-DD HH24:MI:SS 中获取当前时间。默认时区是 UTC+08,因为我的系统可以位于任何时区。

如果你能帮我写c++代码会很有帮助(我没有c++11、14编译器)

我看到了一种解决方案 - 使用时间以 UTC 获取当前时间,然后将 TZ 环境变量操作到您的目标时区。然后使用 localtime_r 转换为该时区的本地时间。

但不确定如何使用适用于 Windows 和 linux 的 c++ 来实现这一点。

【问题讨论】:

  • 我为此使用了较新的 CCTZ 库。可以用吗?
  • CCTZHoward Hinnant's timezone library 都需要在 C++11 中引入的 <chrono>。但是,是的,其中任何一个都可以轻松完成这项工作(在 C++11/14/17 中)。

标签: c++ linux windows time


【解决方案1】:

我建议查看 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

【讨论】:

  • 我不能使用 boost 库..:(任何其他解决方案都会有所帮助
【解决方案2】:

应该适用于大多数平台:

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

}

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2017-04-30
    • 2020-05-27
    • 2016-12-11
    • 2012-02-29
    • 2013-04-18
    相关资源
    最近更新 更多