With Boost datetime how do i create a month string padded with zero?
-
09-06-2021 - |
Domanda
With Boost datetime how do i create a month string padded with zero for the first 9 months?
So I need "05" not "5".
date Date(2012,05,1);
string monthStringAsNumber = lexical_cast<string>(date.Month().as_number());
// returns "5"
string monthStringAsNumberTwo = date.Month().as_short_string();
// returns "Aug"
I would like "05". How do i do this?
Thanks a lot.
Soluzione
You don't really need lexical_cast
The following should work:
stringstream ss;
ss << setw(2) << setfill('0') << date.Month().as_number());
string monthStringAsNumber = ss.str();
or you could just go for this howler:
const string mn[] ={ "01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12" };
const string& monthStringAsNumber = mn[ date.Month().as_number() ];
Altri suggerimenti
In general, if you want to get the date time in some customized format, you could check http://www.boost.org/doc/libs/1_49_0/doc/html/date_time/date_time_io.html, e.g.
#include <boost/date_time.hpp>
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char** argv)
{
boost::gregorian::date date (2012,5,1);
boost::gregorian::date_facet* facet =
new boost::gregorian::date_facet("%Y %m %d");
// ^ yes raw pointer here, and don't delete it.
std::ostringstream ss;
ss.imbue(std::locale(std::locale(), facet));
ss << date;
std::string s = ss.str();
std::cout << s << std::endl; // 2012 05 01
return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow