How can we retrieve the current time in C++?
You can use the time() function from the
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
std::time_t currentTime = std::time(0);
// 转换为本地时间
std::tm* localTime = std::localtime(¤tTime);
// 输出当前时间
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.