【问题标题】:C++ boost get unix timestamp in UTCC ++ boost在UTC中获取unix时间戳
【发布时间】:2016-02-21 21:28:16
【问题描述】:

您好,我正在尝试使用 UTC 中的 boost 来获取自纪元以来经过的时间,但似乎 microsec_clock::universal_time();不返回 UTC 时间,而是返回 PC 时区的时间。

如何使用 boost 获取 UTC 中的当前时间(以毫秒为单位)?

这是我正在使用的代码

const long long unix_timestmap_now()
{ 
   ptime time_t_epoch(date(1970, 1, 1));
   ptime now = microsec_clock::universal_time();
   time_duration diff = now - time_t_epoch;
   return  diff.total_milliseconds();;
}

【问题讨论】:

  • ptime time_t_epoch = boost::posix_time::from_time_t(0); 得到不同的结果吗?

标签: c++ datetime boost


【解决方案1】:

为什么要使用提升?所有需要的(指时间)都移到 C++ 中的 STL 中。

这很重要 - 不是每个人都知道“unix 时间戳”一次在整个世界都是相同的,即如果检查时间在俄罗斯的服务器上,例如在美国的服务器上,则该值将是相同的(当然在两个服务器正确时间的条件下),它的不同之处仅在于其转换为形式的人可以理解,具体取决于服务器设置。当然,如果您不设置时区,反向priobrazovanie 也会有所不同。

cpp.sh上测试

#include <iostream>
#include <chrono>

int main ()
{
  using namespace std::chrono;

  system_clock::time_point tp = system_clock::now();
  system_clock::duration dtn = tp.time_since_epoch();

  std::cout << "current time since epoch, expressed in:" << std::endl;
   std::cout << "milliseconds: " << duration_cast<milliseconds>(dtn).count();
  std::cout << std::endl;

  return 0;
}

【讨论】:

  • 如果您将转换更正为毫秒,我将对此表示赞同::-) duration_cast&lt;milliseconds&gt;(dtn).count()。在 gcc 上除以一百万是正确的,但在 VS、OS X 和 iOS 上都是错误的。始终让&lt;chrono&gt; 为您进行转换。
  • @Howard Hinnant 我更正了,但在 VS 上(如果你的意思是 compiler visual studio)没有错误。
  • 赞成。 VS-2015 system_clock 的周期为 1/10,000,000。要手动将其转换为毫秒,您需要除以 10,000(这就是 duration_cast&lt;milliseconds&gt; 会做的)。
  • 时钟的纪元由实现定义。
猜你喜欢
  • 2017-10-07
  • 2012-11-11
  • 2013-03-20
  • 1970-01-01
  • 2011-08-26
  • 2012-10-01
  • 2015-01-08
  • 2014-03-31
相关资源
最近更新 更多