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

后端 未结 24 1530
刺人心
刺人心 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:27

    This compiled for me on Linux (RHEL) and Windows (x64) targeting g++ and OpenMP:

    #include 
    #include 
    #include 
    #include 
    
    ////////////////////////////////////////////////////////////////////////////////
    //
    //  Reports a time-stamped update to the console; format is:
    //       Name: Update: Year-Month-Day_of_Month Hour:Minute:Second
    //
    ////////////////////////////////////////////////////////////////////////////////
    //
    //  [string] strName  :  name of the update object
    //  [string] strUpdate:  update descripton
    //          
    ////////////////////////////////////////////////////////////////////////////////
    
    void ReportTimeStamp(string strName, string strUpdate)
    {
        try
        {
            #ifdef _WIN64
                //  Current time
                const time_t tStart = time(0);
                //  Current time structure
                struct tm tmStart;
    
                localtime_s(&tmStart, &tStart);
    
                //  Report
                cout << strName << ": " << strUpdate << ": " << (1900 + tmStart.tm_year) << "-" << tmStart.tm_mon << "-" << tmStart.tm_mday << " " << tmStart.tm_hour << ":" << tmStart.tm_min << ":" << tmStart.tm_sec << "\n\n";
            #else
                //  Current time
                const time_t tStart = time(0);
                //  Current time structure
                struct tm* tmStart;
    
                tmStart = localtime(&tStart);
    
                //  Report
                cout << strName << ": " << strUpdate << ": " << (1900 + tmStart->tm_year) << "-" << tmStart->tm_mon << "-" << tmStart->tm_mday << " " << tmStart->tm_hour << ":" << tmStart->tm_min << ":" << tmStart->tm_sec << "\n\n";
            #endif
    
        }
        catch (exception ex)
        {
            cout << "ERROR [ReportTimeStamp] Exception Code:  " << ex.what() << "\n";
        }
    
        return;
    }
    

提交回复
热议问题