How can we retrieve the current time in C++?

You can use the time() function from the header file in C++ to get the current system time. It returns the total number of seconds since January 1, 1970, 0:00:00 UTC. Here is an example code to get the current time.

#include <iostream>
#include <ctime>

int main() {
    // 获取当前时间
    std::time_t currentTime = std::time(0);

    // 转换为本地时间
    std::tm* localTime = std::localtime(&currentTime);

    // 输出当前时间
    std::cout << "当前时间为:" << localTime->tm_year + 1900 << "-" << localTime->tm_mon + 1 << "-" << localTime->tm_mday
        << " " << localTime->tm_hour << ":" << localTime->tm_min << ":" << localTime->tm_sec << std::endl;

    return 0;
}

Running the above code will output the current year, month, day, hour, minute, and second. It is important to note that the localtime() function converts time_t type of time to local time, not UTC time. If UTC time is needed, the gmtime() function can be used.

bannerAds