我想通过网络boost::posix_time::ptime
转移boost::int64_t
。time_duration
。根据{{3}},我可以轻松定义自己的纪元,并仅将ptime
从该参考纪元转移为64位整数。但是如何转换回#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
构造函数采用滴答计数作为参数是私有的。我也对将{{1}}转移到简单数据类型上的任何其他方式感兴趣。
答案 0 :(得分:5)
具有毫秒分辨率的工作解决方案:
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。
答案 1 :(得分:2)
适用于编译boost::datetime
库的最大分辨率(通常为微/纳米):
time_duration time_duration_from_ticks(time_duration::tick_type ticks)
{
return time_duration(
0, // hours
0, // minutes
ticks / time_duration::ticks_per_second(), // seconds
ticks % time_duration::ticks_per_second()); // fractional_seconds
}
(请注意,time_duration::tick_type
是您的int64_t
,如果您设置的提升日期时间仅为微秒分辨率,这是默认设置。)
答案 2 :(得分:0)
微秒分辨率time_duration:
boost::posix_time::microseconds( _ts / TICKS_PER_MICROSECOND )
其中TICKS_PER_MICROSECOND是每微秒的滴答数(例如,如果滴答为百万秒,则为10,如Windows FILETIME中所示)。
毫秒构造函数似乎适用于某些人的原因是它接受一个long的参数类型,在某些编译器中是64位。在MSVC中,它在32位平台上是32位,所以它不起作用。微秒构造函数接受64位整数,该整数应该“足以满足所有人”。