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

后端 未结 5 1982
孤独总比滥情好
孤独总比滥情好 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: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).

提交回复
热议问题