The localtime function is used in processing time to convert a UTC time to a local time:
[Cpp]
# Include <time. h>
Time_t tmNow = time (NULL );
Tm * ptmNow = localtime (& tmNow); // the equivalent value of year, month, day, hour, minute, and second can be obtained from the tm struct.
Here, localtime returns a tm pointer, and the space is controlled by localtime itself. Therefore, if you call this function consecutively, it may be a problem.
In many cases, we process two times at the same time, for example, the start time and end time of the time period. The Code is as follows:
[Cpp]
Time_t tmBegin = 1351118531; // 06:42:11
Time_t tmEnd = 1351218731; // 10:32:11
Tm * ptmBegin = localtime (& tmBegin );
Tm * ptmEnd = localtime (& tmEnd); // The tm structure of the last call will be modified in the second call. If the last data is not saved, it will be lost.
// Tm * ptm3 = gmtime (& tmEnd); // The effect is the same as the preceding statement, and the previous data is also overwritten.
Char ctmBegin1 [26], ctmEnd [26];
Strftime (ctmBegin, 26, "% Y % m % d % H % M % S", ptmBegin); // the time value of tmEnd is output here.
Strftime (ctmEnd, 26, "% Y % m % d % H % M % S", ptmEnd );
/* Related descriptions in MSDN:
Both the 32-bit and 64-bit versions ofgmtime, mktime, mkgmtime, and localtimeall
Use a single tm structure per thread for the conversion. Each call to one of these
Routines destroys the result of the previous call.
*/
Remember that once the localtime function is called, the content in the tm structure should be retrieved immediately:
[Cpp]
Time_t tmBegin = 1351118531; // 06:42:11
Time_t tmEnd = 1351218731; // 10:32:11
Char ctmBegin1 [26], ctmEnd [26];
Tm * ptmBegin = localtime (& tmBegin );
Strftime (ctmBegin, 26, "% Y % m % d % H % M % S", ptmBegin );
Tm * ptmEnd = localtime (& tmEnd );
Strftime (ctmEnd, 26, "% Y % m % d % H % M % S", ptmEnd );
// Tm * ptm3 = gmtime (& tmEnd );