本文最后更新于 2024-12-09,文章内容可能已经过时。

一、C++格式化时间及获取当前时间

#include <iostream>
#include <string>
#include <ctime>

using namespace std;

string getTime() {
    const time_t now = time(nullptr);
    char str[64];
    strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", localtime(&now));
    return str;
}

int main(int argc, char *argv[]) {

    //0.打印当前时间
    const string timeStr = getTime();
    cout << timeStr << endl;
    return 0;
}
2024-12-09 17:32:30

Process finished with exit code 0