How to obtain the current time in C++?

In C++, you can use the ctime library and the chrono library to obtain the current time.

Utilize the ctime library:

#include <iostream>
#include <ctime>

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

    // 将时间转换为字符串形式
    char* dt = ctime(&now);

    // 输出当前时间
    std::cout << "当前时间为: " << dt << std::endl;

    return 0;
}

Utilize the chrono library:

#include <iostream>
#include <chrono>

int main() {
    // 获取当前时间
    auto now = std::chrono::system_clock::now();

    // 将时间转换为时间戳
    auto now_time_t = std::chrono::system_clock::to_time_t(now);
    
    // 将时间戳转换为字符串形式
    char* dt = ctime(&now_time_t);

    // 输出当前时间
    std::cout << "当前时间为: " << dt << std::endl;

    return 0;
}

The choice between these two methods for obtaining the current time depends on personal preference and needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds