如何将boost :: posix_time :: ptime转换为time_t?

ybu*_*ill 42 c++ boost boost-date-time

是否有一些"标准"方式或我能做的最好的是直接通过减去来计算它gregorian::date(1970,1,1)

ybu*_*ill 35

由于@ icecrime的方法转换两次(ptime内部使用线性表示),我决定使用直接计算.这里是:

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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢@jaaw引起我的注意.由于boost 1.58这个功能包含在date_time/posix_time/conversion.hpp,std::time_t to_time_t(ptime pt).

  • 可惜他们没有把它作为图书馆的直接函数调用添加...我想知道原因是什么...... (15认同)
  • 在conversion.hpp 中使用std::time_t posix_time::to_time_t(posix_time::ptime pt) (3认同)
  • 可以使ptime epoch静态而不是计算每次调用. (2认同)
  • 请记住,`ptime`也可以有几个特殊值(`not_a_date_time`,`pos_infin`和`neg_infin`).添加`assert(!t.is_special());`可能是个好主意.(Boost自己的`to_time_t`也不会检查`is_special`.) (2认同)

kgr*_*ffs 15

这是@ ybungalobill方法的变体,它将让你过去2038年,以防万一.:)

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());
}
Run Code Online (Sandbox Code Playgroud)

  • @ybungalobill:问题不在于`time_t`而在于`time_duration :: sec_type`是32位(至少在我的机器上). (2认同)

Nim*_*Nim 14

time_t是用于以秒为单位保持时间的类型(通常是纪元时间).我猜你是在大纪元以后的时间,如果是这样的话,除了你已经减法之外,我还没有意识到直接获得大纪元时间的任何方式.一旦你有了time_duration(减法的结果),你可以调用total_seconds()持续时间并存储它time_t.

顺便说一句.如果你是在大纪元之后,你可以简单地使用gettimeofday()并省去一些头痛!


ice*_*ime 5

我相信你能做的最好的事情就是to_tm用来获得一个tm并将mktime其转换tm成一个time_t.

  • 但我相信mktime有隐含的时区调整(它显示当地时间的纪元数秒) (3认同)