Unix/posix time to local time and more

Unix time to UTC ISO string... could be great for storing in databases.

boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time();

std::string utc_time = boost::posix_time::to_iso_extended_string( now );

...boost ptime from time()
boost::posix_time::ptime now = boost::posix_time::from_time_t( ::time() );

...posix time to local
boost::posix_time::ptime utc_time_to_local( boost::posix_time::ptime pt )

...UTC ISO string back to ptime
boost::posix_time::ptime ptime_from_iso_string( const std::string& t )
 // the allocated object is deleted by std::locale latter
 boost::posix_time::time_input_facet* input_facet = 
  new boost::posix_time::time_input_facet();

 std::stringstream ss; 
 ss.imbue(std::locale(ss.getloc(), input_facet)); 

 boost::posix_time::ptime pt;
 ss >> pt;
 return pt;

...posix time to localized string
std::string ptime_to_localized_string( boost::posix_time::ptime pt )
// the allocated object is deleted by std::locale latter
 boost::posix_time::time_facet *facet = new boost::posix_time::time_facet();
 std::stringstream ss; 
 ss.imbue(std::locale(ss.getloc(), facet));
 ss << pt;
 return ss.str();

No comments:

Post a Comment