我想转让一个boost::posix_time::ptime
通过网络作为boost::int64_t
。根据将 boost::posix_time::ptime 转换为 __int64 的方法 https://stackoverflow.com/questions/1574647/a-way-to-turn-boostposix-timeptime-into-an-int64,我可以轻松定义自己的epoch并且只传输time_duration
从该参考纪元开始作为 64 位整数。但如何转换回ptime
?
#include <iostream>
#include <cassert>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/greg_month.hpp>
using namespace std;
using boost::posix_time::ptime;
using boost::posix_time::time_duration;
using boost::gregorian::date;
int main(int argc, char ** argv){
ptime t = boost::posix_time::microsec_clock::local_time();
// convert to int64_t
ptime myEpoch(date(1970,boost::gregorian::Jan,1));
time_duration myTimeFromEpoch = t - myEpoch;
boost::int64_t myTimeAsInt = myTimeFromEpoch.ticks();
// convert back to ptime
ptime test = myEpoch + time_duration(myTimeAsInt);
assert(test == t);
return 0;
}
这不起作用,因为time_duration
以刻度计数作为参数的构造函数是私有的。我也对任何其他方式简单地转移它感兴趣ptime
超过简单的数据类型。
毫秒分辨率的工作解决方案:
int main(int argc, char ** argv){
ptime t = boost::posix_time::microsec_clock::local_time();
// convert to int64_t
ptime myEpoch(date(1970,boost::gregorian::Jan,1));
time_duration myTimeFromEpoch = t - myEpoch;
boost::int64_t myTimeAsInt = myTimeFromEpoch.total_milliseconds();
// convert back to ptime
ptime test = myEpoch + boost::posix_time::milliseconds(myTimeAsInt);
cout << test << endl;
cout << t << endl;
time_duration diff = test - t;
assert(diff.total_milliseconds()==0);
return 0;
}
谢谢12a6。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)