函數(shù)簡(jiǎn)介
函數(shù)名: time
頭文件:time.h
函數(shù)原型:time_t time(time_t * timer)
功 能: [1]獲取當(dāng)前的系統(tǒng)時(shí)間,返回的結(jié)果是一個(gè)time_t類型,其實(shí)就是一個(gè)大整數(shù),其值表示從UTC(Coordinated Universal Time)時(shí)間1970年1月1日00:00:00(稱為UNIX系統(tǒng)的Epoch時(shí)間)
到當(dāng)前時(shí)刻的秒數(shù)。然后調(diào)用localtime將time_t所表示的UTC時(shí)間轉(zhuǎn)換為本地時(shí)間(我們是+8區(qū),比UTC多8個(gè)小時(shí))并轉(zhuǎn)成struct tm類型,該類型的各數(shù)據(jù)成員分別表示年月日時(shí)分秒。
補(bǔ)充說明:time函數(shù)的原型也可以理解為 long time(long *tloc),
因?yàn)樵趖ime.h這個(gè)頭文件中time_t實(shí)際上就是:
#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ù)獲得日歷時(shí)間。日歷時(shí)間,是用“從一個(gè)標(biāo)準(zhǔn)時(shí)間點(diǎn)到此時(shí)的時(shí)間經(jīng)過的秒數(shù)”來表示的時(shí)間。
這個(gè)標(biāo)準(zhǔn)時(shí)間點(diǎn)對(duì)不同的編譯器來說會(huì)有所不同,但對(duì)一個(gè)編譯系統(tǒng)來說,
這個(gè)標(biāo)準(zhǔn)時(shí)間點(diǎn)是不變的,該編譯系統(tǒng)中的時(shí)間對(duì)應(yīng)的日歷時(shí)間都通過該標(biāo)準(zhǔn)時(shí)間點(diǎn)來衡量,所以可以說日歷時(shí)間是“相對(duì)時(shí)間”,
但是無論你在哪一個(gè)時(shí)區(qū),在同一時(shí)刻對(duì)同一個(gè)標(biāo)準(zhǔn)時(shí)間點(diǎn)來說,日歷時(shí)間都是一樣的。
#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ù)也常用于隨機(jī)數(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)可以獲得當(dāng)前系統(tǒng)時(shí)間或是標(biāo)準(zhǔn)時(shí)間。
#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;
}