Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 960
Dennis Ritchie Avatar asked Dec 19 '12 17:12

Dennis Ritchie


5 Answers

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();
}
like image 75
zaufi Avatar answered Nov 17 '22 11:11

zaufi


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

like image 26
Cookie Avatar answered Nov 17 '22 11:11

Cookie


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

like image 36
Matteo Italia Avatar answered Nov 17 '22 11:11

Matteo Italia


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

like image 1
default Avatar answered Nov 17 '22 10:11

default


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.

like image 1
Bret Kuhns Avatar answered Nov 17 '22 11:11

Bret Kuhns