你能给我一些从 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();
然后使用
将int
转换为string
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);
但这样做的问题是第 1 天将是“1”而不是应有的“01”。
最佳答案
使用日期时间 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();
}
关于c++ - 在 C++ 中获取 "yyyymmdd"日期字符串的最简单方法(允许提升),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13958018/