Dennis Ritchie
Dennis Ritchie

Reputation: 1311

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

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 ints to strings 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.

Upvotes: 7

Views: 7045

Answers (5)

Cookie
Cookie

Reputation: 12652

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

Upvotes: 3

Bret Kuhns
Bret Kuhns

Reputation: 4084

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.

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126777

<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)

Upvotes: 3

default
default

Reputation: 11635

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

Upvotes: 1

zaufi
zaufi

Reputation: 7119

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();
}

Upvotes: 5

Related Questions