Convert int64_t to time_duration

I would like to pass boost::posix_time::ptime over the network as boost::int64_t . According to the Way to turn boost :: posix_time :: ptime into __int64 , I can easily define my own era and transfer only time_duration from this reference era as a 64-bit integer. But how to convert back to 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; } 

This does not work, since the constructor time_duration , which takes the number of ticks as an argument, is private. I am also interested in any other way to simply pass this ptime over simple data types.

+6
c ++ boost time
source share
3 answers

Millisecond resolution working solution:

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

Thanks 12a6.

+5
source share

Works with any maximum resolution your boost::datetime library is compiled with (usually micros / nanos):

 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 } 

(Note that time_duration::tick_type is your int64_t , if , you set the date and time of the increase with a resolution of only microseconds, which is the default.)

+2
source share

With microsecond resolution time_duration:

 boost::posix_time::microseconds( _ts / TICKS_PER_MICROSECOND ) 

where TICKS_PER_MICROSECOND is the number of ticks per microsecond (for example, 10 if the ticks are hectonanoseconds, for example, in Windows FILETIME).

The reason the millisecond constructor seems to work for some people is because it accepts a parameter type of long, which is 64 bits in some compilers. In MSVC, this is 32 bits on 32-bit platforms, so it will not work. The microsecond constructor accepts a 64-bit integer, which should be "enough for everyone."

0
source share

All Articles