Can you name me some dead-easy way of getting the current "yyyymmdd" (e.g. "20121219") string from C++? Boost is allowed, so that should make it easier. I could use ctime
but it's a bit of a pain to set up that structure.
I already did this
boost::gregorian::date current_date(boost::gregorian::day_clock::local_day());
int year_int = current_date.year();
int month_int = current_date.month();
int day_int = current_date.day();
and then converting the int
s to string
s using
std::string year = boost::lexical_cast<std::string>(year_int);
std::string month = boost::lexical_cast<std::string>(month_int);
std::string day = boost::lexical_cast<std::string>(day_int);
But the problem with this is that day 1 will be "1" instead of "01" as it should be.
Use date-time I/O and facets:
/// Convert date operator
std::string operator()(const boost::gregorian::date& d) const
{
std::ostringstream os;
auto* facet(new boost::gregorian::date_facet("%Y%m%d"));
os.imbue(std::locale(os.getloc(), facet));
os << d;
return os.str();
}
As one-liner:
#include <boost/date_time/gregorian/gregorian.hpp>
std::string date = boost::gregorian::to_iso_string(boost::gregorian::day_clock::local_day());
http://www.boost.org/doc/libs/1_57_0/doc/html/date_time/gregorian.html#date_time.gregorian.date_class
<ctime>
is horrible, but actually achieves what you need in an almost straightforward manner:
char out[9];
std::time_t t=std::time(NULL);
std::strftime(out, sizeof(out), "%Y%m%d", std::localtime(&t));
(test)
From boost there are a bunch of format flags to use:
http://www.boost.org/doc/libs/1_52_0/doc/html/date_time/date_time_io.html
A slightly more C++ oriented version of @Matteo Italia's answer would be to use std::put_time
in conjunction with a tm
struct.
std::time_t time = std::time(nullptr);
std::tm* tm = std::localtime(&time);
std::ostringstream ss;
ss << std::put_time(tm, "%Y%m%d");
std::cout << ss.str() << std::endl;
You could, of course, store the result of ss.str()
in a std::string
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With