1. 程式人生 > >c語言標頭檔案time.h

c語言標頭檔案time.h

#include <stdio.h>
#include <time.h>

void main()
{
	time_t sec;       //typedef long time_t
	struct tm * curTime;

	sec = time(NULL);           //獲取時間,從1970.1.1到現在的秒數,也可以寫成 time(&sec);
	curTime = localtime(&sec);  //把sec轉換為當地時間,存於時間結構體curTime中,注意返回值是struct tm* 型別的

	printf("asctime(curTime): %s\n", asctime (curTime));
        //asctime(struct tm*)函式將curTime轉化成標準ASCII時間格式

	printf("ctime(curTime):   %s\n", ctime (&sec));
        //ctime(time_t*)直接將sec轉換成標準時間格式

	printf("%d-%d-%d %d:%d:%d\n", 1900+curTime->tm_year, 1+curTime->tm_mon,
		curTime->tm_mday, curTime->tm_hour, curTime->tm_min, curTime->tm_sec);
		//手動輸出struct tm中的欄位,其中月份加1,年份要加1900,
		//sec記錄的是1970到現在的秒數,為什麼是加1900呢???

	printf("\nsec = %ld\nmktime(curTime) = %ld\n", sec, mktime(curTime));
		//time_t mktime(struct tm*)將curTime反向轉化成1970到現在的秒數
}