Time processing in c++ (1) localtime, localtime_r and localtime_s

There are several functions for dealing with time in C++, which may be used by many C++ programmers, but they may not be completely clear. Here, let me explain first: the use of localtime, localtime_r and localtime_s

1、localtime

localtime is used to obtain the system time, and the precision is seconds.

struct tm *localtime(const time_t * timep)

Among them, the structure of struct tm is as follows:

#ifndef _TM_DEFINED
struct tm {
          int tm_sec;       /* 秒 – 取值区间为[0,59] */
          int tm_min;       /* 分 - 取值区间为[0,59] */
          int tm_hour;      /* 时 - 取值区间为[0,23] */
          int tm_mday;      /* 一个月中的日期 - 取值区间为[1,31] */
          int tm_mon;       /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
          int tm_year;      /* 年份,其值等于实际年份减去1900 */
          int tm_wday;      /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
          int tm_yday;      /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
          int tm_isdst;     /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
          };
#define _TM_DEFINED
#endif

example:

#include <stdio.h>
#include <time.h>
 
int main()
{
    time_t time_seconds = time(0);
    struct tm* now_time = localtime(&time_seconds);
 
    printf("%d-%d-%d %d:%d:%d\n", now_time->tm_year + 1900, now_time->tm_mon + 1,
        now_time->tm_mday, now_time->tm_hour, now_time->tm_min,
        now_time->tm_sec);
}

Results of the:

2、localtime_r

localtime_r is also used to obtain the system time, running on the linux platform.

The function prototype is as follows:

struct tm *localtime_r(const time_t *timep, struct tm *result);

Results of the:

3、localtime_s

When using the localtime function under windows, if "SDL check" is turned on, an error will be reported:

 Error message:

Because localtime is not thread-safe, when using localtime, we only need to define a pointer, and do not need to apply for space for the pointer; and the pointer must point to the memory space before it can be used. In fact, the action of applying for space is completed by the function itself, so In the case of multi-threading, if another thread calls this function, the data of the struct tm structure pointed to by the pointer will change.
Let's look at an example using localtime_s:

#include <iostream>
#include <time.h>
 
int main()
{
	time_t time_seconds = time(0);
	struct tm now_time;
	localtime_s(&now_time,&time_seconds);
 
	printf("%d-%d-%d %d:%d:%d\n", now_time.tm_year + 1900, now_time.tm_mon + 1,
		now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
}

Guess you like

Origin blog.csdn.net/mars21/article/details/131663543