Linux C獲取時間函式例項
例項詳解Linux下C獲取時間函式的程式碼。
一、time
標頭檔案:
#include <time.h>
原型:
time_t time(time_t *t)
time_t的定義:
typedef __darwin_time_t time_t;
typedef long __darwin_time_t;
返回值:UTC(coordinated universal time)時間1970年1月1日00時00分00秒(也稱為Linux系統的Epoch時間)到當前時刻的秒數
例:1
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time(NULL);
printf("自 1970-01-01 起的小時數 = %ld\n", seconds/3600);
return(0);
}
二、localtime localtime_r
標頭檔案:
#include <time.h>
原型:
struct tm *localtime(const time_t *timep)
原型:
struct tm *localtime_r(const time_t *timep, struct tm *result);
結構體tm
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
/* 夏令時識別符號,實行夏令時的時候,tm_isdst為正。不實行夏令時的進候,tm_isdst為0;不瞭解情況時,tm_isdst()為負。*/
};
localtime 與 localtime_r區別
localtime 不是可重入 localtime_r 可重入
例2:
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
//注意下面兩行的區別
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd);
char szTmp[50] = {0};
strftime(szTmp,50,"%H:%M:%S",ptm);
char szEnd[50] = {0};
strftime(szEnd,50,"%H:%M:%S",ptmEnd);
printf("%s/n",szTmp);
printf("%s/n",szEnd);
return 0;
}
最後出來的結果是:
20:30:32
20:30:32
例3:
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
struct tm ptm = { 0 };
struct tm ptmEnd = { 0 };
localtime_r(&tNow, &ptm);
localtime_r(&tEnd, &ptmEnd);
char szTmp[50] = {0};
strftime(szTmp,50,"%H:%M:%S",&ptm);
char szEnd[50] = {0};
strftime(szEnd,50,"%H:%M:%S",&ptmEnd);
printf("%s\n",szTmp);
printf("%s\n",szEnd);
return 0;
}
最後出來的結果是:
20:03:21
20:33:21
三、gettimeofday
標頭檔案:
#include <sys/time.h>
原型:
int gettimeofday(struct timeval*tv, struct timezone *tz)
tv:是儲存獲取時間結果的結構體
struct timeval{
long int tv_sec; // 秒數
long int tv_usec; // 微秒數
}
tz:用於儲存時區結果
struct timezone{
int tz_minuteswest;/*格林威治時間往西方的時差*/
int tz_dsttime;/*DST 時間的修正方式*/
}
返回值:成功返回0,失敗返回-1,錯誤程式碼保存於errno中
四、mktime
標頭檔案:
#include <time.h>
原型:
time_t mktime(struct tm *tm)
返回值:1970年1月1日以來持續時間的秒數,發生錯誤時返回-1。
例4:
#include<stdio.h>
#include<time.h>
int main(void)
{
time_t timep;
struct tm* p;
time(&timep);
printf("time():%d\n",timep);
p=localtime(&timep);
timep=mktime(p);
printf("time()->localtime()->mktime():%d\n",timep);
return 0;
}
輸出:
time():1541246772
time()->localtime()->mktime():1541246772