localtime、localtime_s、localtime_r的使用

(1)、localtime用來獲取系統時間,精度爲秒

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

函數原型爲struct tm *localtime(const time_t * timep)

需要包含頭文件:#include <time.h>
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()爲負。*/

(2)localtime_r也是用來獲取系統時間,運行於linux平臺下

函數原型爲struct tm *localtime_r(const time_t *timep, struct tm *result);

#include <stdio.h>
#include <time.h>

int main()
{
    time_t time_seconds = time(0);
    struct tm now_time;
    localtime_r(&time_seconds, &now_time);

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

(3)localtime_s也是用來獲取系統時間,運行於windows平臺下,與localtime_r只有參數順序不一樣

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


          會什麼有了localtime還要有其他兩個函數呢,因爲localtime並不是線程安全的,觀察localtime和localtime_r的調用發現,localtime在使用時,我們只需定義一個指針,並不需要爲指針申請空間,而指針必須要指向內存空間纔可以使用,其實申請空間的動作由函數自己完成,這樣在多線程的情況下,如果有另一個線程調用了這個函數,那麼指針指向的struct tm結構體的數據就會改變。

        在localtime_s與localtime_r調用時,定義的是struct tm的結構體,獲取到的時間已經保存在struct tm中,並不會受其他線程的影響。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章