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

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

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

24条回答
  •  旧时难觅i
    2020-11-22 07:19

    You can try the following cross-platform code to get current date/time:

    #include 
    #include 
    #include 
    #include 
    
    // Get current date/time, format is YYYY-MM-DD.HH:mm:ss
    const std::string currentDateTime() {
        time_t     now = time(0);
        struct tm  tstruct;
        char       buf[80];
        tstruct = *localtime(&now);
        // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
        // for more information about date/time format
        strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
    
        return buf;
    }
    
    int main() {
        std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
        getchar();  // wait for keyboard input
    }
    

    Output:

    currentDateTime()=2012-05-06.21:47:59
    

    Please visit here for more information about date/time format

提交回复
热议问题