The easiest way (boost allowed) to get a "yyyymmdd" date string in C++

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)

Tags:

C++