time(), time_t, localtime(), localtime_r()的理解和用法

time_t的定义:

typedef __darwin_time_t	time_t; 
typedef long	__darwin_time_t;	/* time() */
从定义可以看出,timez_t实际上的数据类型是long。


time()

time_t time ( time_t * ptr_time );
 参数和返回值都是time_t object。

如果参数为空,则返回当前时间距1970年1月1日00:00点 UTC的秒数;

    long secondsSince1970 = time(NULL);
    printf("It has been %ld seconds since 1970\n", secondsSince1970);

It has been 1413202571 seconds since 1970

如果参数不为空,此时返回值和参数都为当前时间距1970年1月1日00:00点 UTC的秒数。

time_t t;
time_t sec = 1000000000;
t = time(&sec);
printf("sec = %ld, t = %ld\n", sec, t);

sec = 1413202571, t = 1413202571

localtime()

struct tm * localtime ( const time_t * ptr_time );
 tm是一个包含了年月日时分秒的结构,定义如下:

struct tm {
    int tm_sec; //seconds after the minute[0-60]
    int tm_min; //minutes after the hour[0-59]
    int tm_hour; //hours since midnight[0-23]
    int tm_mday; //day of the month[0-31]
    int tm_mon; //months since January[0-11]
    int tm_year; //years since 1900
    int tm_wday; //days since Sunday[0-6]
    int tm_yday; //days since January
    int tm_isdst; //Daylight Savings Time flag
    int tm_gmtoff; //offset from CUT in seconds
    char *tm_zone; //timezone abbreviation
};

 一般搭配time()函数使用,可以得到当前时间的年月日时分秒等。该函数所得时间为当前时区。

 

    long secondsSince1970 = time(NULL);
    printf("It has been %ld seconds since 1970\n", secondsSince1970);
    
    struct tm now;
    localtime_r(&secondsSince1970, &now);
    printf("Current time is %d-%d-%d %d:%d:%d\n", now.tm_year + 1900, now.tm_mon + 1, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec);

It has been 1413203631 seconds since 1970

Current time is 2014-10-13 20:33:51

localtime_r()

struct tm *localtime_r(const time_t *restrict timer,
       struct tm *restrict result);
 由于localtime()是不重入的函数,因此是thread not safe的。如果多次调用这个函数,下一次返回的参数会把上一次返回的参数覆盖掉。。。就是说
struct tm* ptm = localtime(&tNow);  
struct tm* ptmEnd = localtime(&tEnd); 
 这里的ptm == ptmEnd

还有同样碉堡功能的时间函数还有asctime()ctime()gmtime()
所以有了localtime_r()的存在,localtime()的可重入版本。当要多次使用的时候,最好用localtime_r()


参考文献:

http://www.codingunit.com/c-reference-time-h-structure-tm

http://pubs.opengroup.org/onlinepubs/009695399/functions/localtime.html

http://blog.csdn.net/markman101/article/details/7861415

你可能感兴趣的:(time(), time_t, localtime(), localtime_r()的理解和用法)