2011-07-31

Convert a boost::posix_time::ptime to a std::time_t value

Often you need a std::time_t value or a UNIX timestamp which is the number of seconds elapsed since January 1st 1970 but what you start with is a boost::posix_time::ptime (from the Boost C++ library). Here is how you can convert it:

#include "ctime"
#include "boost/date_time/posix_time/posix_time_types.hpp"
std::time_t convert(const boost::posix_time::ptime& t)
{
   static const boost::posix_time::ptime epoch(
         boost::gregorian::date(1970,1,1) );
   const boost::posix_time::time_duration::sec_type x(
         (t - epoch).total_seconds() );
   return x;
}

Here is a small test program that illustrates it's use by converting the current UTC time:

#include "ctime"
#include "boost/date_time/posix_time/posix_time_types.hpp"
std::time_t convert(const boost::posix_time::ptime& t)
{
   static const boost::posix_time::ptime epoch(
         boost::gregorian::date(1970,1,1) );
   const boost::posix_time::time_duration::sec_type x(
         (t - epoch).total_seconds() );
   return x;
}
#include "iostream"
int main()
{
   const boost::posix_time::ptime t(
         boost::posix_time::second_clock::universal_time() );
   std::cout << convert(t) << std::endl;
   return 0;
}

0 kommentarer:

Post a Comment