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

后端 未结 5 1966
孤独总比滥情好
孤独总比滥情好 2020-12-05 06:49

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

相关标签:
5条回答
  • 2020-12-05 07:02

    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.

    0 讨论(0)
  • 2020-12-05 07:06

    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!

    0 讨论(0)
  • 2020-12-05 07:11

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

    0 讨论(0)
  • 2020-12-05 07:16

    These 2 lines should do it.

    tm td_tm = to_tm(pt);
    time_t tt = mktime(&td_tm);
    
    0 讨论(0)
  • 2020-12-05 07:18

    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());
    }
    
    0 讨论(0)
提交回复
热议问题