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)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…