c++

c++ strptime函数的用法是什么

小亿
160
2024-02-26 10:06:28
栏目: 编程语言

在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结构体中。然后输出解析后的年、月、日、时、分、秒信息。

0
看了该问题的人还看了