c++ strftime
时间: 2023-10-18 22:57:31 浏览: 53
`std::strftime` 是 C++ 标准库中的一个函数,用于将时间格式化为指定的字符串。它位于 `<ctime>` 头文件中,并提供了以下函数原型:
```cpp
size_t strftime(char* str, size_t count, const char* format, const struct tm* timeptr);
```
参数解释如下:
- `str`:指向字符数组的指针,用于存储格式化后的时间字符串。
- `count`:`str` 数组的大小。
- `format`:格式化字符串,用于指定输出时间的格式。
- `timeptr`:指向 `tm` 结构体的指针,表示要格式化的时间。
下面是一个使用 `std::strftime` 的示例代码,将当前时间格式化为字符串:
```cpp
#include <iostream>
#include <ctime>
int main() {
std::time_t currentTime = std::time(nullptr);
struct std::tm* timeInfo = std::localtime(¤tTime);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeInfo);
std::cout << "当前时间为:" << buffer << std::endl;
return 0;
}
```
在上述示例中,我们首先使用 `std::time` 函数获取当前时间的时间戳。然后,使用 `std::localtime` 函数将时间戳转换为 `tm` 结构体表示的本地时间。接着,我们将格式化的时间字符串存储在字符数组 `buffer` 中,使用 `std::strftime` 函数进行格式化操作。最后,将格式化后的时间字符串输出到控制台。
在 `std::strftime` 的第三个参数中,可以使用各种格式化字符串来指定输出时间的格式,如 `%Y` 表示年份、`%m` 表示月份、`%d` 表示日期、`%H` 表示小时(24 小时制)、`%M` 表示分钟、`%S` 表示秒等。你可以根据具体需求,调整格式化字符串以满足你的要求。