Reputation: 6853
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.
Upvotes: 0
Views: 11890
Reputation: 3336
boost::gregorian::date d(boost::gregorian::day_clock::local_day());
char date[10];
sprintf ( date, "%d/%d/%d", static_cast<short>(d.month()), static_cast<short>(d.day()), static_cast<short>(d.year()) );
Upvotes: 3
Reputation: 47418
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.imbue(fmt);
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);
is.imbue(fmt2);
boost::gregorian::date date;
is >> date;
return date;
}
Upvotes: 11
Reputation: 769
A better option would be to use a std::stringstream and output the date's month, day and year numbers separately and adding slashes between yourself.
Upvotes: 1