函數:time;localtime;gmtime;ctime;asctime;
1)time
time()函數聲明位於time.h中,
原型是:time_t time(time *timeptr)
作用是:
返回1970-1-1日0時0分0秒到調用時刻的時長,如果參數不是空指針,那麼返回值也會存儲到參數自變量指向的位置。就是我們常說的日曆時間。
#include <stdio.h> #include <stddef.h> #include <time.h>
int main(void)
{ time_t timer; struct tm *tblock; timer = time(NULL); printf("%08X\n",timer); tblock = localtime(&timer); printf("Local time is: %s\n",asctime(tblock)); return 0; }
localtime()函數聲明位於time.h中
原型是:struct tm *localtime(const time_t *timer);
作用是:
將日曆時間(1970-1-1日0時0分0秒開始的時長)轉換爲本地時區的日期和時間結構。些函數的參數不是秒數本身,而是一個指向此數值的指針,成功調用此函數後可以通過struct tm結構體的各成員訪問傳入參數對應的本地時間
struct tm
{
int tm_sec; /*0-59的秒數*/
int tm_min; /* 0-59的分數 */
int tm_hour; /* 0-23的小時數 */
int tm_mday; /*1-31的日期數*/
int tm_mon; /*0-11的月數*/
int tm_year; /* 1900~至今的年數 */
int tm_wday; /*0-6的星期數*/
int tm_yday; /*0-365的天數*/
int tm_isdst; /*日光節約
};
#include <stdio.h>
#include <time.h>
int main(int argc,char **argv)
{
time_t timep; struct tm *localp; struct tm *gmp; timep=time(NULL); localp=localtime(&timep); /* 獲取當前時間 */ gmp=gmtime(&timep); /* 獲取當前時間 */
printf("%x\n",timep); printf("localtime:%2d-%02d-%02d %02d:%02d:%02d\n",(1900+localp->tm_year), (1+localp->tm_mon),localp->tm_mday,localp->tm_hour, localp->tm_min,localp->tm_sec);//注意這裏年+1900,月+1
printf("gmtime: %2d-%02d-%02d %02d:%02d:%02d\n",(1900+gmp->tm_year), (1+gmp->tm_mon),gmp->tm_mday,gmp->tm_hour, gmp->tm_min,gmp->tm_sec);//注意這裏年+1900,月+1
printf("local today's date and time(asctime): %s\n", asctime(localp)); //打印日誌時間。 printf("gm today's date and time(asctime): %s\n", asctime(gmp)); //打印日誌時間。 printf("time today's date and time: %s\n", ctime(&timep)); //打印日誌時間。
return 0;
}
輸出:
4f23baff
localtime:2012-01-28 09:08:15 gmtime: 2012-01-28 09:08:15
local today's date and time(asctime): Sat Jan 28 09:08:15 2012
gm today's date and time(asctime): Sat Jan 28 09:08:15 2012
time today's date and time: Sat Jan 28 17:08:15 2012