C++: how to get the actual time with time and localtime?

后端 未结 4 751
暖寄归人
暖寄归人 2021-02-19 03:41

I\'m looking for a way to save the time in a HH::MM::SS fashion in C++. I saw here that they are many solutions and after a little research I opted for time and

4条回答
  •  深忆病人
    2021-02-19 04:24

    localtime has what is best considered a legacy interface. It can't be used in multithreaded code, for example. In a multithreaded environment, you can use localtime_r under Posix or localtime_s under Windows. Otherwise, all you have to do is save the results:

    tm then = *localtime( &t1 );
    //  ...
    tm now = *localtime( &t2 );
    

    It would probably be more idiomatic, however, to only call localtime
    immediately before formatting the output, e.g.:

    std::string
    timestampToString( time_t timeAndDate )
    {
        char results[100];
        if ( strftime( results, sizeof( results ), "%Y-%m-%d, %H:%M:%S", 
                    localtime( &timeAndDate) ) == 0 ) {
            assert( 0 );
        }
        return results;
    }
    

    and then writing:

    std::cout << formatTime( t1 ) << std::endl;
    

    (You could also create a more generic formatting function, which took the format as an argument.)

提交回复
热议问题