Can increase gregorian date and increase posix time correctly calculate unixtime?

I am trying to write a simple timestamping system that provides landmark seconds and fractional seconds from current time. I am using boost library and have something like this:

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); 

and then use the following elements to retrieve era values:

 dur.total_seconds(); dur.fractional_seconds(); 

In particular, will this return the correct unix time? If not, any suggestions on how to fix this? Thanks.

+6
source share
1 answer

Yes, this should work, but for sure there is always experimental evidence:

 #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'; } 

I get

Linux / GCC

  boost: 1361502964.664746 ctime: 1361502964 posix: 1361502964.664818326 

Sun / Sun Studio

  boost: 1361503762.775609 ctime: 1361503762 posix: 1361503762.775661600 

AIX / XLC

  boost: 1361503891.342930 ctime: 1361503891 posix: 1361503891.342946000 

and even Windows / Visual Studio

  boost: 1361504377.084231 ctime: 1361504377 

Everyone seems to agree on how many seconds have passed since date(1970,1,1)

+5
source

All Articles