函數(shù)簡介
函數(shù)名: time
頭文件:time.h
函數(shù)原型:time_t time(time_t * timer)
功 能: [1]獲取當前的系統(tǒng)時間,返回的結(jié)果是一個time_t類型,其實就是一個大整數(shù),其值表示從UTC(Coordinated Universal Time)時間1970年1月1日00:00:00(稱為UNIX系統(tǒng)的Epoch時間)
到當前時刻的秒數(shù)。然后調(diào)用localtime將time_t所表示的UTC時間轉(zhuǎn)換為本地時間(我們是+8區(qū),比UTC多8個小時)并轉(zhuǎn)成struct tm類型,該類型的各數(shù)據(jù)成員分別表示年月日時分秒。
補充說明:time函數(shù)的原型也可以理解為 long time(long *tloc),
因為在time.h這個頭文件中time_t實際上就是:
#ifndef _TIME_T_DEFINED
typedef long time_t; /* time value */
#define _TIME_T_DEFINED /* avoid multiple def's of time_t */
#endif
即long。
函數(shù)應(yīng)用舉例
程序例1: time函數(shù)獲得日歷時間。日歷時間,是用“從一個標準時間點到此時的時間經(jīng)過的秒數(shù)”來表示的時間。
這個標準時間點對不同的編譯器來說會有所不同,但對一個編譯系統(tǒng)來說,
這個標準時間點是不變的,該編譯系統(tǒng)中的時間對應(yīng)的日歷時間都通過該標準時間點來衡量,所以可以說日歷時間是“相對時間”,
但是無論你在哪一個時區(qū),在同一時刻對同一個標準時間點來說,日歷時間都是一樣的。
#include <time.h>
#include <stdio.h>
#include <dos.h>
int main(void)
{
time_t t;
t = time(NULL);
printf("The number of seconds since January 1, 1970 is %ld",t);
return 0;
}
程序例2:
//time函數(shù)也常用于隨機數(shù)的生成,用日歷時間作為種子。
#include <stdio.h>
#include <time.h>
#include<stdlib.h>
int main(void)
{
int i;
srand((unsigned) time(NULL));
printf("ten random numbers from 0 to 99\n\n");
for(i=0;i<10;i++)
{
printf("%d\n",rand()%100);
}
return 0;
}
程序例3:
用time()函數(shù)結(jié)合其他函數(shù)(如:localtime、gmtime、asctime、ctime)可以獲得當前系統(tǒng)時間或是標準時間。
#include <stdio.h>
#include <stddef.h>
#include <time.h>
int main(void)
{
time_t timer;//time_t就是long int 類型
struct tm *tblock;
timer = time(NULL);//這一句也可以改成time(&timer);
tblock = localtime(&timer);
printf("Local time is: %s\n",asctime(tblock));
return 0;
}