Notes for using the localtime function in C ++

Source: Internet
Author: User

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 );

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.