Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a datetime to string using boost?

Tags:

I want to format a date/time to a string using boost.

Starting with the current date/time:

ptime now = second_clock::universal_time(); 

and ending up with a wstring containing the date/time in this format:

%Y%m%d_%H%M%S 

Can you show me the code to achieve this? Thanks.

like image 573
mackenir Avatar asked Feb 16 '11 15:02

mackenir


2 Answers

For whatever it is worth, here is the function that I wrote to do this:

#include "boost/date_time/posix_time/posix_time.hpp" #include <iostream> #include <sstream>  std::wstring FormatTime(boost::posix_time::ptime now) {   using namespace boost::posix_time;   static std::locale loc(std::wcout.getloc(),                          new wtime_facet(L"%Y%m%d_%H%M%S"));    std::basic_stringstream<wchar_t> wss;   wss.imbue(loc);   wss << now;   return wss.str(); }  int main() {   using namespace boost::posix_time;   ptime now = second_clock::universal_time();    std::wstring ws(FormatTime(now));   std::wcout << ws << std::endl;   sleep(2);   now = second_clock::universal_time();   ws = FormatTime(now);   std::wcout << ws << std::endl;  } 

The output of this program was:

20111130_142732 20111130_142734 

I found these links useful:

  • How to format date time object with format dd/mm/yyyy?
  • http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.time_facet
  • http://www.cplusplus.com/reference/iostream/stringstream/str/
like image 131
Robᵩ Avatar answered Sep 21 '22 13:09

Robᵩ


// create your date boost::gregorian::date d(2009, 1, 7);   // create your formatting boost::gregorian::date_facet *df = new boost::gregorian::date_facet("%Y%m%d_%H%M%S");   // set your formatting ostringstream is; is.imbue(std::locale(is.getloc(), df)); is << d << endl;  // get string cout << "output :" << is.str() << endl; 
like image 22
Validus Oculus Avatar answered Sep 19 '22 13:09

Validus Oculus