Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost simple human readable date time of now

Tags:

c++

boost

Anyone know how to get a simple date format from boost of the current time to a local system?

boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time();
boost::posix_time::time_facet *facet = new boost::posix_time::time_facet("%d-%m-%Y %H:%M:%S");

I've seen examples that say to use cout.imbue but I just want a simple string.

like image 847
Bluebaron Avatar asked Oct 26 '11 15:10

Bluebaron


2 Answers

you can try this code:

void FormatDateTime(
    std::string const&              format,
    boost::posix_time::ptime const& date_time,
    std::string&                    result)
  {
    boost::posix_time::time_facet * facet =
      new boost::posix_time::time_facet(format.c_str());
    std::ostringstream stream;
    stream.imbue(std::locale(stream.getloc(), facet));
    stream << date_time;
    result = stream.str();
  }

Set format to "%d-%m-%Y %H:%M:%S" or whatever facet you want.

For the local time, use boost::posix_time::second_clock::local_time() as the second argument (date_time).

like image 138
0x26res Avatar answered Nov 09 '22 11:11

0x26res


I know it's too late but for searchers like me:

#include <boost/format.hpp>

const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();

const boost::wformat f = boost::wformat(L"%02d.%02d.%s  %02d:%02d")
                % now.date().year_month_day().dayas_number()
                % now.date().year_month_day().month.as_number()
                % now.date().year_month_day().year
                % now.time_of_day().hours()
                % now.time_of_day().minutes();

const std::wstring result = f.str();  // "21.06.2013  14:38"
like image 34
aleX Avatar answered Nov 09 '22 12:11

aleX