c++boostboost-date-time

Boost date_time output format being ignored


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?


Solution

  • 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();