bre*_*don 6 c++ boost timestamp date unix-timestamp
我正在尝试编写一个简单的时间戳系统,它提供了当前时间的纪元秒和小数秒.我正在使用boost库,有类似这样的东西:
const boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
boost::posix_time::ptime time() {
boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
return now;
}
boost::posix_time::time_duration dur = (time() - epoch);
Run Code Online (Sandbox Code Playgroud)
然后使用以下元素提取纪元值:
dur.total_seconds();
dur.fractional_seconds();
Run Code Online (Sandbox Code Playgroud)
具体来说,这将返回适当的unix时间吗?如果没有,有关如何纠正它的任何建议?谢谢.
是的,这应该有效,但是,可以肯定的是,总有实验证据:
#include <iostream>
#include <time.h>
#include <boost/date_time.hpp>
namespace bpt = boost::posix_time;
namespace bg = boost::gregorian;
int main()
{
bpt::time_duration dur = bpt::microsec_clock::universal_time()
- bpt::ptime(bg::date(1970, 1, 1));
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
std::cout << std::setfill('0')
<< " boost: " << dur.total_seconds() << '.' << std::setw(6)
<< dur.fractional_seconds() << '\n'
<< " ctime: " << time(NULL) << '\n'
<< " posix: " << ts.tv_sec << '.' << std::setw(9)
<< ts.tv_nsec << '\n';
}
Run Code Online (Sandbox Code Playgroud)
我明白了
Linux的/ GCC
boost: 1361502964.664746
ctime: 1361502964
posix: 1361502964.664818326
Run Code Online (Sandbox Code Playgroud)
Sun/Sun Studio
boost: 1361503762.775609
ctime: 1361503762
posix: 1361503762.775661600
Run Code Online (Sandbox Code Playgroud)
AIX/XLC
boost: 1361503891.342930
ctime: 1361503891
posix: 1361503891.342946000
Run Code Online (Sandbox Code Playgroud)
甚至是Windows/Visual Studio
boost: 1361504377.084231
ctime: 1361504377
Run Code Online (Sandbox Code Playgroud)
看起来他们都同意从那以后经过了多少秒 date(1970,1,1)