1. 程式人生 > >常用時間函式

常用時間函式

比較常用的時間函式有time(),localtime(),asctime(),和gmtime()。

函式time()的原型為:

time_t time(time_t *time);

函式time()返回系統的當前日曆時間,如果系統丟失時間設定,則函式返回-1。

對函式time的呼叫,既可以使用空指標,也可以使用指向time_t型別變數的指標。

函式localtime()的原型為:

struct tm*localtime(const time_t *time);

函式localtime(),指向以tm結構形式time(時間)的一個指標。該事件表示為本地時間(計算機上的時間)。

變元time指標一般通過呼叫函式time()獲得。

函式asctime()的原型為:

char *asctime(const struct tm*ptr);

函式asctime()返回指向一個串的指標,其中儲存ptr所指結構中儲存的資訊的變換形式,

具體格式如下:

day month date hours:minutes:seconds year \n \0

例如:

Fir Apr 15 9:15:12 2015

由ptr指向的結構一般是通過呼叫localtime()或gmtime()得到的。

儲存asctime()返回的格式化時間串空間是靜態空間變數,因此每次呼叫asctime()

時都用新串沖掉該靜態字元陣列中的原值。希望儲存以前的結果是,應該複製它到別處。

函式gmtime的原型為:

struct tm *gmtime(const time_t *time);

函式gmtime()返回一個指標,指標指向以tm結構形式的分解格式time。時間用UTC(coordinated

universal time)即格林尼治時間表示,time指標一般是通過呼叫time()取得。

如果系統不支援UTC,則該函式返回空指標。

#include<stdio.h>
#include<time.h>
int main()
{
	struct tm*local;
	time_t tm;
	tm=time(NULL);
	local=localtime(&tm);
	printf("Local time and date: %s\n",asctime(local));
	local=gmtime(&tm);
	printf("UTC time and date: %s\n",asctime(local));
	return 0;
}