在C++中,strptime函數用于將日期時間字符串解析為tm結構體,其原型如下:
char *strptime(const char *buf, const char *format, struct tm *tm);
參數說明:
函數返回值:
示例:
#include <iostream>
#include <ctime>
int main() {
const char *dateStr = "2022-01-01 12:30:45";
struct tm tm;
char *endPtr = strptime(dateStr, "%Y-%m-%d %H:%M:%S", &tm);
if (endPtr != NULL) {
std::cout << "Year: " << tm.tm_year + 1900 << std::endl;
std::cout << "Month: " << tm.tm_mon + 1 << std::endl;
std::cout << "Day: " << tm.tm_mday << std::endl;
std::cout << "Hour: " << tm.tm_hour << std::endl;
std::cout << "Minute: " << tm.tm_min << std::endl;
std::cout << "Second: " << tm.tm_sec << std::endl;
} else {
std::cout << "Parsing failed." << std::endl;
}
return 0;
}
在上面的示例中,我們使用strptime函數將日期時間字符串"2022-01-01 12:30:45"按照"%Y-%m-%d %H:%M:%S"的格式解析,并將解析后的日期時間信息存儲在tm結構體中。然后輸出解析后的年、月、日、時、分、秒信息。