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

后端 未结 4 738
暖寄归人
暖寄归人 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 03:59

    the localtime() call stores the results in an internal buffer.

    Every time you call it you overwrite the buffer.
    An alternative solution would be to make a copy of the buffer.

    time_t      t1  = time(0);           // get time now
    struct tm* now  = localtime( & t1 ); // convert to local time
    struct tm  copy = *now;              // make a local copy.
     //     ^^^ notice no star.
    

    But note: The only time you should be converting to local time is when you display the value. At all other times you should just keep the time as UTC (for storage and manipulation). Since you are only converting the objects for display convert then print immediately and then things will not go wrong.

提交回复
热议问题