How to convert timestamp of fractional epoch (double) to std :: chrono :: time_point?

I have a fractional era timestamp, represented as a double , which I would like to convert to the corresponding std::chrono::time_point . The era is the usual UNIX era from 01/01/1970. I know that there is std::chrono::system_clock::from_time_t , but a time_t does not have a fractional part. What would be the best way to do this using C ++ 11?

This question is related to unix timestamp for raising :: posix_time :: ptime , except that it is asking for C ++ 11, not Boost.

+8
c ++ unix-timestamp c ++ 11 chrono boost-date-time
source share
1 answer

Assuming the era is the same as the clock type, you can use the duration with the double representation and convert to the duration used by this watch.

 // change period to appropriate units - I'm assuming seconds typedef std::chrono::duration<double, std::ratio<1>> d_seconds; d_seconds since_epoch_full(324324.342); auto since_epoch = std::chrono::duration_cast<clock::duration>(since_epoch_full); clock::time_point point(since_epoch); 

This should be good for any calculations related to this watch, since you use the same precision as the watch, but may lose some of the conversion accuracy. If you do not want to lose this, you will have to use the time_point specialization, which uses this type of duration double . And then use this in your calculations (of course, with all the caveats of floating point mathematics).

 typedef std::chrono::time_point<clock, d_seconds> d_time_point; 

However, this will complicate any calculations using the same clock, as this will require conversions. To make this easier, you can create your own watch shell, which makes conversions, and use it:

 template <typename Clock> struct my_clock_with_doubles { typedef double rep; typedef std::ratio<1> period; typedef std::chrono::duration<rep, period> duration; typedef std::chrono::time_point<my_clock_with_doubles<Clock>> time_point; static const bool is_steady = Clock::is_steady; static time_point now() noexcept { return time_point(std::chrono::duration_cast<duration>( Clock::now().time_since_epoch() )); } static time_t to_time_t(const time_point& t) noexcept { return Clock::to_time_t(typename Clock::time_point( std::chrono::duration_cast<typename Clock::duration>( t.time_since_epoch() ) )); } static time_point from_time_t(time_t t) noexcept { return time_point(std::chrono::duration_cast<duration>( Clock::from_time_t(t).time_since_epoch() )); } }; 
+12
source share

All Articles