在C++中获取"yyyymmdd"日期字符串的最简单方法(允许提升)

Den*_*hie 5 c++

你能说出一些从C++中获取当前"yyyymmdd"(例如"20121219")字符串的简单方法吗?允许Boost,因此应该更容易.我可以使用,ctime但设置该结构有点痛苦.

我已经这样做了

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();
Run Code Online (Sandbox Code Playgroud)

然后使用ints将strings 转换为s

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);
Run Code Online (Sandbox Code Playgroud)

但问题是第1天应该是"1"而不是"01".

zau*_*ufi 5

使用日期时间I/O和方面:

/// 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();
}
Run Code Online (Sandbox Code Playgroud)