所有的unix系統都使用同一個時間和日期的起點:格林尼治時間(GMT)1970年1月1日午夜0點
時間通過一個預定義的類型time_t來處理,在linux系統中,它是一個長整型。包含在time.h中。
#include<time.h>
time_t time(time_t *tloc);
通過time函數可以得到底層的時間值,它返回的是從紀元開始至今的秒數。如果tloc不是一個null 指標,time函數還會把傳回值寫入到tloc指標指向的位置。
#include <time.h>#include <stdio.h>#include <unistd.h>#include <stdlib.h>int main(){ int i; time_t the_time; for(i = 1; i <= 10; i++) { the_time = time((time_t *)0); printf("The time is %ld\n", the_time); sleep(2); } exit(0);}
#include<time.h>
double difftime(time_t time1,time_t time2);
difftime函數是計算兩個時間值之間的差,並將time1-time2的值作為浮點數返回。
為了提供更有意義的時間和日期,你需要把時間值轉換為可讀的時間和日期,有一些標準函數可以做到這些。
#include<time.h>
struct tm *gmtime(const time_t timeval);
tm結構被定義為下面所示的成員
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* 是否夏令時*/
下面這個gmtime.c利用tm結構gmtime列印當前的時間和日期
#include <time.h>#include <stdio.h>#include <stdlib.h>int main(){ struct tm *tm_ptr; time_t the_time; (void) time(&the_time); tm_ptr = gmtime(&the_time); printf("Raw time is %ld\n", the_time); printf("gmtime gives:\n"); printf("date: %02d/%02d/%02d\n", tm_ptr->tm_year, tm_ptr->tm_mon+1, tm_ptr->tm_mday); printf("time: %02d:%02d:%02d\n", tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec); exit(0);}
要查看本地的時間,你需要使用localtime函數
#include<time.h>
struct tm *localtime(const time_t *timaval);
要把已分解出來的tm結構再轉換為原始的time_t時間值,你可以使用mktime函數:
#include<time.h>
time_t mktime(struct tm *timeptr);
如果結構tm結構不能表示time_t的值,mktime但會-1
為了得到更友好的時間和日期,像date命令輸出那樣。你可以使用asctime函數和ctime函數。
#include<time.h>
char *asctime(const struct tm *timeptr);
char *ctime(struct time_t *timeval);
#include <time.h>#include <stdio.h>#include <stdlib.h>int main(){ time_t timeval; (void)time(&timeval); printf("The date is: %s", ctime(&timeval)); exit(0);}