Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert boost::posix_time::ptime to time_t?

Is there some "standard" way or the best I can do is to compute it directly by subtracting from gregorian::date(1970,1,1)?

like image 617
Yakov Galka Avatar asked Dec 16 '10 14:12

Yakov Galka


2 Answers

Since @icecrime's method converts twice (ptime uses linear representation internally), I've decided to use direct computation instead. Here it is:

time_t to_time_t(boost::posix_time::ptime t) {     using namespace boost::posix_time;     ptime epoch(boost::gregorian::date(1970,1,1));     time_duration::sec_type x = (t - epoch).total_seconds();      // ... check overflow here ...      return time_t(x); } 

EDIT: Thanks @jaaw for bringing this to my attention. Since boost 1.58 this function is included in date_time/posix_time/conversion.hpp, std::time_t to_time_t(ptime pt).

like image 128
Yakov Galka Avatar answered Sep 19 '22 22:09

Yakov Galka


time_t is the type used to hold time in seconds (typically epoch time). I'm guessing you are after epoch time, if so I'm not aware of any way in boost of actually getting epoch time directly, aside from the subtraction you have already. Once you have a time_duration (result of the subtraction), you can call total_seconds() on the duration and store that in time_t.

btw. if you are after epoch time, you could simple use gettimeofday() and save yourself some headache!

like image 21
Nim Avatar answered Sep 22 '22 22:09

Nim