參照:http://www.linuxdiyf.com/viewarticle.php?id=81130
常用的資料類型
time_t 一般用來儲存國際化時間,用time()函數可直接擷取到;
結構體:tm 一般用來儲存本地時間,可通過將time_t格式轉化而來;
結構體:time_val 一般用來儲存計數型的時間(秒/毫秒);
有些也用struct tim,但好像不如time_val好用。
常用的時間函數及標頭檔
包含標頭檔:#include <time.h>
1. 功能:將時間轉化為字元
char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
2. 功能:將time_t類型轉為tm結構體,即轉化為格林尼治時間
struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
3. 功能:將國際時間轉為本地時間
struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
4. 功能:計算時間差
double difftime(time_t time1, time_t time0);
包含標頭檔:#include <sys/time.h>
5. 功能:擷取時間
int
gettimeofday(struct timeval *tv, struct timezone *tz);
6. 功能:設定時間
int settimeofday(const struct timeval *tv, const struct timezone *tz);
擷取系統時間
1.可以用localtime()函數分別擷取年月日時分秒的數值。
在所有的UNIX下,都有個time()的函數;
格式:time_t time(time_t *t);
這個函數會傳回格林尼治時間,如果t是non-null,它將會把時間值填入t中
樣本:
#include <time.h>#include <stdio.h>int main(){ time_t now; struct tm * timenow; time(&now); //printf("International time is %s\n", ctime(&now)); printf("International time is %s\n", asctime(gmtime(&now))); timenow=localtime(&now); printf("Local time is %s\n", asctime(timenow));}
說明:
time()函數讀取現在的時間(國際標準時間,而非北京時間),然後傳值給now;
localtime()函數將國際標準時間轉化為本地時間(本地所設地區),返回結果給timenow;
asctime()函數將tm結構體類型的轉化為字元;
2. 可以用gettimeofday()函數擷取精確時間(精確到毫秒)
對某些需要較高精準度的需求,Linux提供了gettimeofday()。
格式:int gettimeofday(struct timeval * tv,struct timezone *tz);
其中,第一個參數用來返回資訊,第二個參數一般設為0(指標可直接賦0,linux下的特色);
gettimeofday()會把目前的時間有tv所指的結構返回,本地時區資訊(一般沒什麼用,設為0)則放到tz所指的結構中。
樣本:
#include <stdlib.h>#include <sys/time.h>#include <stdio.h>bool time_subtract(struct timeval * result, struct timeval * x, struct timeval * y){ if(x->tv_sec<y->tv_sec) return false; result->tv_sec=x->tv_sec-y->tv_sec; result->tv_usec=x->tv_usec-y->tv_usec;}int main(){ struct timeval start, stop, diff; gettimeofday(&start, 0); for(int i=0; i<10000000; i++) {} gettimeofday(&stop, 0); time_subtract(&diff, &start, &stop); printf("共用時%d ms\n",diff.tv_usec);}
附加:
1. 結構體:tm
struct tm
{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
tm_sec表「秒」數,在[0,61]之間,多出來的兩秒是用來處理跳秒問題用的。
tm_min表「分」數,在[0,59]之間。
tm_hour表「時」數,在[0,23]之間。
tm_mday表「本月第幾日」,在[1,31]之間。
tm_mon表「本年第幾月」,在[0,11]之間。
tm_year要加1900表示那一年。
tm_wday表「本第幾日」,在[0,6]之間。
tm_yday表「本年第幾日」,在[0,365]之間,閏年有366日。
tm_isdst表是否為「日光節約時間」。
2. 結構體:timeval
struct timeval
{
int tv_sec;
int tv_usec;
};
tv_sec表示從淩晨開始算起的秒數;
tv_usec表示從淩晨算起的毫秒數;