将boost :: posix_time :: ptime转换为NTP时间戳

时间:2022-09-09 08:44:42

I have a device which gives me boost::posix_time::ptime thorugh its API. To sychronize with other Data I need the time as NTP timestamp, differentiated in NTP seconds and NTP fract_seconds.

我有一个设备,它给我boost :: posix_time :: ptime thorugh它的API。要与其他数据同步,我需要将时间作为NTP时间戳,在NTP秒和NTP fract_seconds之间进行区分。

I tried something like:

我试过类似的东西:

#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;
  }

But it does not give me the correct results? Any help appreciated.

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

1 个解决方案

#1


0  

NOTE: boost::ptime may not have the necessary granularity for NTP. However what you can do to obtain the quantity needed (seconds and fractional is as follows)

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

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

Now you should have two 32-bit values from which you can construct the necessary NTP timestamp.

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

#1


0  

NOTE: boost::ptime may not have the necessary granularity for NTP. However what you can do to obtain the quantity needed (seconds and fractional is as follows)

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

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

Now you should have two 32-bit values from which you can construct the necessary NTP timestamp.

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