注:該貼轉(zhuǎn)自:https://zhidao.baidu.com/question/558299804.html
C語言中讀取系統(tǒng)時(shí)間的函數(shù)為time()带欢,其函數(shù)原型為:#include <time.h>time_t time( time_t * ) ;
time_t就是long涧窒,函數(shù)返回從1970年1月1日(MFC是1899年12月31日)0時(shí)0分0秒帖努,到現(xiàn)在的的秒數(shù)雨涛。
可以調(diào)用ctime()函數(shù)進(jìn)行時(shí)間轉(zhuǎn)換輸出:char * ctime(const time_t *timer);
將日歷時(shí)間轉(zhuǎn)換成本地時(shí)間尼酿,按年月日格式集乔,進(jìn)行輸出锌云,如:Wed Sep 23 08:43:03 2015C語言還提供了將秒數(shù)轉(zhuǎn)換成相應(yīng)的時(shí)間結(jié)構(gòu)的函數(shù):
struct tm * gmtime(const time_t *timer);?//將日歷時(shí)間轉(zhuǎn)化為世界標(biāo)準(zhǔn)時(shí)間(即格林尼治時(shí)間)
struct tm * localtime(const time_t * timer);?//將日歷時(shí)間轉(zhuǎn)為本地時(shí)間將通過time()函數(shù)返回的值,轉(zhuǎn)成時(shí)間結(jié)構(gòu)structtm :
struct tm {int tm_sec; /* 秒 – 取值區(qū)間為[0,59] */
int tm_min; /* 分 - 取值區(qū)間為[0,59] */
int tm_hour; /* 時(shí) - 取值區(qū)間為[0,23] */
int tm_mday; /* 一個(gè)月中的日期 - 取值區(qū)間為[1,31] */
int tm_mon; /* 月份(從一月開始褂乍,0代表一月) - 取值區(qū)間為[0,11] */
int tm_year; /* 年份持隧,其值等于實(shí)際年份減去1900 */
int tm_wday; /* 星期 – 取值區(qū)間為[0,6],其中0代表星期天逃片,1代表星期一屡拨,以此類推 */
int tm_yday; /* 從每年的1月1日開始的天數(shù) – 取值區(qū)間為[0,365],其中0代表1月1日褥实,1代表1月2日呀狼,以此類推 */
int tm_isdst; /* 夏令時(shí)標(biāo)識(shí)符,實(shí)行夏令時(shí)的時(shí)候损离,tm_isdst為正哥艇。不實(shí)行夏令時(shí)的進(jìn)候,tm_isdst為0僻澎;不了解情況時(shí)貌踏,tm_isdst()為負(fù)十饥。*/};
編程者可以根據(jù)程序功能的情況,靈活的進(jìn)行日期的讀取與輸出了祖乳。
下面給出一段簡單的代碼:
#include
int main()
{
????time_t timep;
????struct tm *p;
????time (&timep);
????p=gmtime(&timep);
????printf("%d\n",p->tm_sec); /*獲取當(dāng)前秒*/
????printf("%d\n",p->tm_min); /*獲取當(dāng)前分*/
????printf("%d\n",8+p->tm_hour);/*獲取當(dāng)前時(shí),這里獲取西方的時(shí)間,剛好相差八個(gè)小時(shí)*/
????printf("%d\n",p->tm_mday);/*獲取當(dāng)前月份日數(shù),范圍是1-31*/
????printf("%d\n",1+p->tm_mon);/*獲取當(dāng)前月份,范圍是0-11,所以要加1*/
????printf("%d\n",1900+p->tm_year);/*獲取當(dāng)前年份,從1900開始逗堵,所以要加1900*/
????printf("%d\n",p->tm_yday); /*從今年1月1日算起至今的天數(shù),范圍為0-365*/
}