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

标签 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();

然后使用

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/

相关文章:

c++ - 如何声明返回标准迭代器的函数原型(prototype)?

c++ - diab 5.7 编译器中的逻辑 AND 运算符返回非 bool 类型

c++强制隐式转换作为参数传递

带硬盘的 C++ IO

c++ - C++程序如何从Microsoft Excel文件中读取数据

c++ - 使用 OpenCV 以 JPG 格式编码图像以避免重影效果

c++ - 将 C/C++ 代码从 Linux 移植到 Windows 的最佳环境

c++ - 如果我定义带有非常量参数的复制构造函数和 operator= ,我仍然会得到默认的复制构造函数和 operator= 吗?

C++:使用模板中的两个相同类型名构造海峡

c++ - 使用 zlib 从 pdf 中提取文本