开发者

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 grego开发者_如何学运维rian::date(1970,1,1)?


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


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!


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


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.


These 2 lines should do it.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜