【问题标题】:Convert boost::posix_time::ptime to NTP Timestamp将 boost::posix_time::ptime 转换为 NTP 时间戳
【发布时间】:2011-08-17 09:22:03
【问题描述】:

我有一个设备可以通过它的 API 为我提供 boost::posix_time::ptime。为了与其他数据同步,我需要时间作为 NTP 时间戳,以 NTP 秒和 NTP fract_seconds 区分。

我尝试了类似的方法:

#include "boost/date_time/posix_time/posix_time.hpp"
#include <iostream>

using namespace std;

using boost::posix_time::ptime;
using boost::posix_time::time_duration;
using boost::gregorian::date;

int main() 
  {
    ptime t = boost::posix_time::microsec_clock::local_time();

    ptime myEpoch(date(1900,boost::gregorian::Jan,1));

    time_duration myTimeFromEpoch = t - myEpoch;

    boost::uint64_t myTimeAsInt = myTimeFromEpoch.ticks();

    cout << myTimeAsInt << endl;

    boost::uint32_t seconds = (boost::uint32_t)((myTimeAsInt >> 32) & 0xFFFFFFFF);

    boost::uint32_t fraction = (boost::uint32_t)(myTimeAsInt & 0xFFFFFFFF);

    cout << seconds << endl;
    cout << fraction << endl;

    return 0;
  }

但它没有给我正确的结果?任何帮助表示赞赏。

【问题讨论】:

  • @person 投票结束,不确定是否与 time_t 与 NTP 不同。

标签: c++ boost posix ntp


【解决方案1】:

注意:boost::ptime may 没有必要的 NTP 粒度。但是你可以做些什么来获得所需的数量(秒和小数如下)

long seconds = myTimeFromEpoch.total_seconds();
long fractional = myTimeFromEpoch.fractional_seconds()

现在您应该有两个 32 位值,您可以从中构造必要的 NTP 时间戳。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多