How to convert boost :: gregorian :: date in mm / dd / aaaa format and vice versa?


Boost has several functions converting to other string formats described here, but there is no conversion into the necessary mm/dd/yyyy format. Currently I am doing it the following way:

 std::string dateAsMMDDYYYY( const boost::gregorian::date& date )
    std::string yyyymmdd = boost::gregorian::to_iso_string( date );
    std::string ret = yyyymmdd.substr(4,2) + "/" + yyyymmdd.substr(6,2) + "/" + yyyymmdd.substr(0,4);
    return ret;

i.e. just cutting the numbers out of the value returned by to_iso_string(). This seems very rude, and I am looking for a more elegant way to perform this conversion. Also I need an advice about how to perform a backward conversion (i.e. from 'mm/dd/yyyy' string to boost::gregorian::date)

Any help is appreciated. Thanks in advance.

boost has fairly versatile date/time IO facilities

const std::locale fmt(std::locale::classic(),
                      new boost::gregorian::date_facet("%m/%d/%Y"));
std::string dateAsMMDDYYYY( const boost::gregorian::date& date )
    std::ostringstream os;
    os << date;
    return os.str();

Inverse conversion:

const std::locale fmt2(std::locale::classic(),
                       new boost::gregorian::date_input_facet("%m/%d/%Y"));
boost::gregorian::date MMDDYYYYasDate( const std::string& str)
    std::istringstream is(str);
    boost::gregorian::date date;
    is >> date;
    return date;