How do I convert boost::posix_time::ptime to time_

2019-01-13 20:17发布

问题:

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

回答1:

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!



回答2:

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).



回答3:

Here's a variation of @ybungalobill's method that will get you past 2038, just in case. :)

int64_t rax::ToPosix64(const boost::posix_time::ptime& pt)
{
  using namespace boost::posix_time;
  static ptime epoch(boost::gregorian::date(1970, 1, 1));
  time_duration diff(pt - epoch);
  return (diff.ticks() / diff.ticks_per_second());
}


回答4:

I believe the best you can do is using to_tm to get a tm and mktime to convert the tm to a time_t.



回答5:

These 2 lines should do it.

tm td_tm = to_tm(pt);
time_t tt = mktime(&td_tm);