0

I am having trouble trying to work out how to get Boost to format a date/time object as a string. I am trying to set a format specifier but it is ignored and keeps outputting the date in a predefined style.

It's probably easier to explain by demonstration, so here is some sample code showing the problem:

#include <boost/date_time.hpp>
#include <iostream>

int main(void)
{
    int i = 1485324852;
    boost::posix_time::ptime pt = boost::posix_time::from_time_t(i);

    boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();
    output_facet->format("%d/%m/%Y %H:%M");

    std::stringstream ss;
    ss.imbue(std::locale(std::locale::classic(), output_facet));
    ss << pt;

    std::string strTime = ss.str();
    std::cout << "Time " << i << " converted to UI string: " << strTime << "\n";

    return 0;
}

It gives me this output:

Time 1485324852 converted to UI string: 2017-Jan-25 06:14:12

What I expected is:

Time 1485324852 converted to UI string: 25/01/2017 16:14

I have told the output_facet to use the %d/%m/%Y %H:%M format specifier as per the example given in the Boost docs, yet this is being ignored.

I cannot see where I am going wrong with setting the format. It is probably something obvious so is anyone able to point it out to me?

Malvineous
  • 25,144
  • 16
  • 116
  • 151
  • see http://stackoverflow.com/questions/1904317/how-to-format-date-time-object-with-format-dd-mm-yyyy – Asalle Jan 25 '17 at 09:40

2 Answers2

2

I think you're mixing the local_date and posix_time.

Adding at the end of your code solves your problem and prints the desired format:

boost::local_time::local_date_time ldt(boost::local_time::not_a_date_time);
ss >> ldt;
ss.str("");
ss << ldt;
std::cout << ss.str() << std::endl;

Nevertheless, if you want to print the desired format using posix_time you need to change:

boost::local_time::local_time_facet* output_facet = new boost::local_time::local_time_facet();

to:

 boost::posix_time::time_facet *output_facet = new boost::posix_time::time_facet();
jgorostegui
  • 1,290
  • 1
  • 8
  • 13
1

Okay, I reproduced it, I cannot get the right output with your code. Here is snippet, can give the right output. The only difference I see is local_time_facet vs. time_facet.

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

using namespace boost::posix_time;
using namespace std;

int main(int argc, char **argv) {
  boost::posix_time::ptime now = boost::posix_time::from_time_t(123456789);
  time_facet *facet = new time_facet("%d/%b/%Y %H:%M:%S");
  cout.imbue(locale(cout.getloc(), facet));
  cout <<  now << endl;
}
Asalle
  • 1,239
  • 19
  • 41
  • I'm not sure what you mean - I'm not using `local_time`. If you make your suggested change to the code above, does it compile for you and produce the expected `dd/mm/yyyy` format? – Malvineous Jan 25 '17 at 09:11