#include <iostream> #include <ctime> int main(int argc, char *argv[]) { struct tm timeinfo; char cur_time[] = "current time: 2021-09-06 23:50:13"; // 解析时间到timeinfo中 strptime(cur_time, "current time: %Y-%m-%d %H:%M:%S", &timeinfo); printf("%s\n", asctime(&timeinfo)); return 0; }
稍微复杂些的格式:
#include <iostream> #include <ctime> int main(int argc, char *argv[]) { struct tm timeinfo; char cur_time[] = "2021年 Sep 6 Mon 23:50:13"; strptime(cur_time, "%Y年 %b %d %a %H:%M:%S %Y-%m-%d %H:%M:%S", &timeinfo); size_t buf_size = 80; char buf[buf_size]; strftime(buf, buf_size, "%Y-%m-%d %H:%M:%S", &timeinfo); printf("%s\n", buf); return 0; }
支持的格式化字符串: