一:相關函數原型
#include <time.h> time_t time(time_t *t); char *asctime(const struct tm *tm); char *ctime(const time_t *timep); struct tm *gmtime(const time_t *timep); struct tm *localtime(const time_t *timep); time_t mktime(struct tm *tm); char *strptime(const char *s, const char *format, struct tm *tm); size_t strftime(char *s, size_t max, const char *format, const struct tm *tm); struct tm { int tm_sec; /* seconds */ int tm_min; /* minutes */ int tm_hour; /* hours */ int tm_mday; /* day of the month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of the week */ int tm_yday; /* day in the year */ int tm_isdst; /* daylight saving time */ };
二:API歸類
time()用於當前時間戳,如果t不爲空那麼返回的時間戳同樣也會存儲在t中。
asctime()傳入一個tm的時間結構體,返回這個可讀性好的時間字符串
ctime()功能和asctime相同,但是ctime功能更強,可以將time_t類型的時間戳轉換
成可讀性好的時間字符串。
gmtime()傳入一個time_t 類型的時間值,將其轉換成一個時間tm結構體,但是gmtime 有一個缺點返回的時候格式是UTC時間,不是當前主機時區的時間。
localtime()和gmtime功能相同,只不過localtime返回的是當前主機時區的時間。
mktime()傳入一個tm結構體將其轉換成time_t類型的時間戳。
strftime()傳入一個tm結構體和格式化字符串,根據格式化字符串將其格式會相對應的時間格式。
strptime()傳入一個時間字符串,指定其格式,將其轉換成tm的時間結構體
asctime() ctime()可分爲一類,針對不同的參數使用不同的函數。
gmtime() localtime()分爲一類,根據是否對時區又要求來使用。
strftime() strptime()分爲一類,處理格式化時間字符串。
time() 用於獲取當前時間
三:API函數相關使用
#include<stdio.h> #include<stdlib.h> #define _XOPEN_SOURCE #這句沒有的話,編譯會有警告信息,GUN庫中沒有strptime聲明 #include<time.h> time_t return_current_time(); void print_time(time_t tdata); int main ( int argc, char *argv[] ) { print_time(return_current_time()); return EXIT_SUCCESS; } void print_time(time_t tdata) { char *wday[]={"SUn","Mon","Tue","Wed","Thu","Fri","Sat"}; struct tm *pt; time_t tmp; char buf[256]; //指定輸出字符串的格式 char *format = "%A %d %B, %I:%S %p"; // pt = gmtime(&tdata); pt = localtime(&tdata); printf("%ld:convert to time:\n",tdata); printf("isdst:%d\n",pt->tm_isdst); printf("year:%d年\n",pt->tm_year+1900); printf("mon:%d月\n",pt->tm_mon+1); printf("mday:%d日\n",pt->tm_mday); printf("week:%s\n",wday[pt->tm_wday]); printf("hour:%d小時\n",pt->tm_hour); printf("min:%d分鐘\n",pt->tm_min); printf("sec:%d秒\n",pt->tm_sec); printf("asctime的輸出\n"); printf("%s\n",asctime(pt)); printf("Ctime 輸出:\n"); printf("%s\n",ctime(&tdata)); printf("mktime將tm結構轉換成time_t類型的值\n"); if((tmp = mktime(pt)) == -1){ perror("mktime error:"); exit(1); } printf("mktime convert to time_t:%ld\n",tmp); printf("strftime的使用:\n"); if(strftime(buf,256,format,pt) == -1){ perror("strftime error:"); exit(1); } printf("%s\n",buf); printf("strptime的使用:\n"); #buf中存放的是指定format格式的時間字符串,根據其fotamt再轉換成tm結構體 strptime(buf,format,pt); } #獲取當前的時間 time_t return_current_time () { return time((time_t *)0); }