??? 首先介紹基本的時(shí)間概念。時(shí)間一般分為兩種,一種是本地時(shí)間(Local Time),一種是協(xié)調(diào)世界時(shí)間(Coordinated Universal Time ,UTC),也就是傳說中的格林威治時(shí)間。本地時(shí)間與UTC時(shí)間之間的差即為時(shí)差,比如,北京時(shí)間(東八區(qū))比UTC時(shí)間晚8個小時(shí)。
??? C運(yùn)行庫中處理時(shí)間的函數(shù)主要是這四個:
????
[cpp] view plaincopy print?
time_t?time(??
????????????time_t?*timer);??
???
time_t time(time_t *timer);
??? time_t類型為32位或64位整型,具體類型由編譯系統(tǒng)決定。此函數(shù)用來獲得從1970年1月1日子夜(這個時(shí)刻在不同的CRT實(shí)現(xiàn)中可能會不一樣)到當(dāng)前時(shí)刻以來所流逝的時(shí)間,以秒為單位。這個時(shí)間差叫做日歷時(shí)間(Calendar Time )。
struct tm {int tm_sec; /* seconds after the minute - [0,59] */int tm_min; /* minutes after the hour - [0,59] */int tm_hour; /* hours since midnight - [0,23] */int tm_mday; /* day of the month - [1,31] */int tm_mon; /* months since January - [0,11] */int tm_year; /* years since 1900 */int tm_wday; /* days since Sunday - [0,6] */int tm_yday; /* days since January 1 - [0,365] */int tm_isdst; /* daylight savings time flag */
};
#include <stdlib.h>
#include <stdio.h>
#include <time.h>int main()
{struct tm tmLocal, tmUTC;time_t tNow;//Get current calendar timetime(&tNow);printf("Time Now from time(): %llu/n", tNow); //Get current local timelocaltime_s(&tmLocal, &tNow); printf("Local Time(YYYY-MM-DD HH:MM:SS): %d-%d-%d %d:%d:%d/n", tmLocal.tm_year + 1900, tmLocal.tm_mon,tmLocal.tm_mday, tmLocal.tm_hour, tmLocal.tm_min, tmLocal.tm_sec);//Get UTC time corresponding to current local time, and tmLocal.tm_hour - tmUTC.tm_hour = 8gmtime_s(&tmUTC, &tNow); printf("UTC Time (YYYY-MM-DD HH:MM:SS): %d-%d-%d %d:%d:%d/n", tmUTC.tm_year + 1900, tmUTC.tm_mon,tmUTC.tm_mday, tmUTC.tm_hour, tmUTC.tm_min, tmUTC.tm_sec);//convert tmLocal to calendar timetNow = mktime(&tmLocal); printf("Time Now from mktime(): %llu/n", tNow);return EXIT_SUCCESS;
}
????18行g(shù)mtime_s函數(shù)將將日歷時(shí)間轉(zhuǎn)換為對應(yīng)的UTC的tm時(shí)間,如輸出結(jié)果第三行顯示。很容易看出,第二,三行輸出的時(shí)間相差8小時(shí),因?yàn)槲以跂|八區(qū)。如果你修改自己電腦的時(shí)區(qū)(在控制面板的Date and Time中修改),再運(yùn)行此程序,比較兩次的運(yùn)行結(jié)果,你就可以更好的理解了。