C++ 如何将 boost::posix_time::ptime 转换为 time_t?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4461586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert boost::posix_time::ptime to time_t?
提问by ybungalobill
Is there some "standard" way or the best I can do is to compute it directly by subtracting from gregorian::date(1970,1,1)
?
有没有一些“标准”的方法,或者我能做的最好的事情是直接通过减去来计算它gregorian::date(1970,1,1)
?
采纳答案by Nim
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
.
time_t
是用于以秒为单位保存时间的类型(通常是纪元时间)。我猜你是在纪元时间之后,如果是这样的话,除了你已经进行的减法之外,我不知道有任何方法可以直接直接获得纪元时间。一旦有了time_duration
(减法的结果),就可以调用total_seconds()
持续时间并将其存储在time_t
.
btw. if you are after epoch time, you could simple use gettimeofday()
and save yourself some headache!
顺便提一句。如果你是在时代之后,你可以简单地使用gettimeofday()
并节省一些头痛!
回答by ybungalobill
Since @icecrime's method converts twice (ptime uses linear representation internally), I've decided to use direct computation instead. Here it is:
由于@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);
}
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)
.
编辑:感谢@jaaw 引起我的注意。自 boost 1.58 起,此函数包含在date_time/posix_time/conversion.hpp
, 中std::time_t to_time_t(ptime pt)
。
回答by kgriffs
Here's a variation of @ybungalobill's method that will get you past 2038, just in case. :)
这是@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());
}
回答by icecrime
回答by Ramesh
These 2 lines should do it.
这 2 行应该这样做。
tm td_tm = to_tm(pt);
time_t tt = mktime(&td_tm);