如何将 boost::posix_time::ptime 转换为 time_t?
是否有一些“标准”方法或者我能做的最好的方法是通过从 gregorian::date(1970,1,1) 中减去来直接计算它?
Is there some "standard" way or the best I can do is to compute it directly by subtracting from gregorian::date(1970,1,1)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于@icecrime的方法转换两次(ptime内部使用线性表示),我决定使用直接计算。这是:
编辑:感谢@jaaw 让我注意到这一点。自 boost 1.58 起,此函数包含在
date_time/posix_time/conversion.hpp
、std::time_t to_time_t(ptime pt)
中。Since @icecrime's method converts twice (ptime uses linear representation internally), I've decided to use direct computation instead. Here it is:
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
是用于保存以秒为单位的时间(通常是纪元时间)的类型。我猜你是在纪元时间之后,如果是这样,除了你已经进行的减法之外,我不知道有任何方法可以直接直接获得纪元时间。获得time_duration
(减法结果)后,您可以对持续时间调用total_seconds()
并将其存储在time_t
中。顺便提一句。如果您在纪元时间之后,您可以简单地使用
gettimeofday()
来避免一些头痛!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 atime_duration
(result of the subtraction), you can calltotal_seconds()
on the duration and store that intime_t
.btw. if you are after epoch time, you could simple use
gettimeofday()
and save yourself some headache!这是 @ybungalobill 方法的一个变体,可以让你度过 2038 年,以防万一。 :)
Here's a variation of @ybungalobill's method that will get you past 2038, just in case. :)
我相信你能做的最好的事情就是使用
to_tm
获取tm
和mktime
将tm
转换为time_t
。I believe the best you can do is using
to_tm
to get atm
andmktime
to convert thetm
to atime_t
.这两行应该可以做到。
These 2 lines should do it.