How to get current time and date in C++?

后端 未结 24 1485
刺人心
刺人心 2020-11-22 06:55

Is there a cross-platform way to get the current date and time in C++?

24条回答
  •  旧巷少年郎
    2020-11-22 07:19

    In C++ 11 you can use std::chrono::system_clock::now()

    Example (copied from en.cppreference.com):

    #include 
    #include 
    #include     
    
    int main()
    {
        auto start = std::chrono::system_clock::now();
        // Some computation here
        auto end = std::chrono::system_clock::now();
    
        std::chrono::duration elapsed_seconds = end-start;
        std::time_t end_time = std::chrono::system_clock::to_time_t(end);
    
        std::cout << "finished computation at " << std::ctime(&end_time)
                  << "elapsed time: " << elapsed_seconds.count() << "s\n";
    }
    

    This should print something like this:

    finished computation at Mon Oct  2 00:59:08 2017
    elapsed time: 1.88232s
    

提交回复
热议问题