在 c++ 中读取日期中的月份部分

Reading the month part in the date in c++

本文关键字:份部 取日期 c++ 读取      更新时间:2023-10-16

我有两个日期,即文件创建日期和系统日期,均为 int 格式

        "20120304","20120404" which is something like YYYYMMDD.

我只想将这两个日期的 MM 部分作为整数从函数返回。

请提出一些例子

谢谢

因为它是int类型使用int mm=(yyyymmdd/100)%100

虽然我更喜欢@keety的答案,但还有另一种方法。您可以使用字符串流:

例如:

#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

因此,在您将字符串作为字符串变量中的YYYYMMDD之后。 substr(4,2)将是你的月份。您可以稍后使用 strtol 转换回整数。

如果它们总是采用 YYYYMMDD 格式,则取 [4] 处的子字符串作为长度 2。