一、時間相關說明 格林威治時間表示0時區的標準時間。其他時區的時間和此標準時間均有時間差。UTC(UniversalTime Coordinated)是世界協調時間,是格林威治時間在互聯網中的表示方法 二、標準C語言時間函數 1、time(取得本地目前的時間秒數) #include time_ttime(time_t *t); 函數說明 此函數會返回從公元1970年1月1日的UTC時間從0時0分0秒(Epoch,linux紀元)算起到現在所經過的秒數。如果t并非空指針的話,此函數也會將返回值存到t指針所指的內存。 返回值 成功則返回秒數,失敗則返回((time_t)-1)值,錯誤原因存于errno中。 time_t定義為longint 范例 #include mian() { longint seconds= time((time_t*)NULL); printf(“%d\n”,seconds); } 執行 9.73E+08 2、gmtime(根據本地時間取得目前的UTC時間) #include structtm*gmtime(const time_t*timep); 函數說明 gmtime()將參數timep 所指的time_t 結構中的信息轉換成真實世界所使用的時間日期表示方法,然后將結果由結構tm返回。 結構tm的定義為 structtm { inttm_sec; inttm_min; inttm_hour; inttm_mday; inttm_mon; inttm_year; inttm_wday; inttm_yday; inttm_isdst; }; inttm_sec 代表目前秒數,正常范圍為0-59,但允許至61秒 inttm_min 代表目前分數,范圍0-59 inttm_hour 從午夜算起的時數,范圍為0-23 inttm_mday 目前月份的日數,范圍01-31 inttm_mon 代表目前月份,從一月算起,范圍從0-11 inttm_year 從1900年算起至今的年數 inttm_wday 一星期的日數,從星期一算起,范圍為0-6 inttm_yday 從今年1月1日算起至今的天數,范圍為0-365 inttm_isdst 日光節約時間的旗標 此函數返回的時間日期未經時區轉換,而是UTC時間。 返回值 返回結構tm代表目前UTC 時間 范例 #include main(){ char*wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; time_ttimep; structtm *p; time(&timep); p=gmtime(&timep); printf(“%d%d%d”,(1900+p->tm_year),(1+p->tm_mon),p->tm_mday); printf(“%s%d;%d;%d\n”,wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec); } 執行 2000/10/28 Sat 8:15:38 3、localtime(取得當地目前UTC時間和日期) #include structtm *localtime(const time_t * timep); 函數說明 localtime()將參數timep所指的time_t結構中的信息轉換成真實世界所使用的時間日期表示方法,然后將結果由結構tm返回。結構tm的定義請參考gmtime()。此函數返回的時間日期已經轉換成當地時區。 返回值 返回結構tm代表目前的當地時間。 范例 #include main(){ char*wday[]={“Sun”,”Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”}; time_ttimep; structtm *p; time(&timep); p=localtime(&timep); printf(“%d%d%d ”, (1900+p->tm_year),( l+p->tm_mon), p->tm_mday); printf(“%s%d:%d:%d\n”,wday[p->tm_wday],p->tm_hour, p->tm_min, p->tm_sec); } 執行 2000/10/28 Sat 11:12:22 4、ctime(將時間和日期以字符串格式表示) #include char*ctime(const time_t *timep); 函數說明 ctime()將參數timep所指的time_t結構中的信息轉換成真實世界所使用的時間日期表示方法,然后將結果以字符串形態返回。此函數已經由時區轉換成當地時間,字符串格式為“WedJun 30 21 :49 :08 1993\n”。若再調用相關的時間日期函數,此字符串可能會被破壞。 返回值 返回一字符串表示目前當地的時間日期。 范例 #include main() { time_ttimep; time(&timep); printf(“%s”,ctime(&timep)); } 執行 Sat Oct 28 10 : 12 : 05 2000 5、asctime(將時間和日期以字符串格式表示) #include char* asctime(const struct tm * timeptr); 函數說明 asctime()將參數timeptr所指的tm結構中的信息轉換成真實世界所使用的時間日期表示方法,然后將結果以字符串形態返回。此函數已經由時區轉換成當地時間,字符串格式為:“WedJun 30 21:49:08 1993\n” 返回值 若再調用相關的時間日期函數,此字符串可能會被破壞。此函數與ctime不同處在于傳入的參數是不同的結構。 附加說明 返回一字符串表示目前當地的時間日期。 范例 #include main() { time_ttimep; time(&timep); printf(“%s”,asctime(gmtime(&timep))); } 執行 Sat Oct 28 02:10:06 2000 6、mktime(將時間結構數據轉換成經過的秒數) #include time_tmktime(strcut tm * timeptr); 函數說明 mktime()用來將參數timeptr所指的tm結構數據轉換成從公元1970年1月1日0時0分0 秒算起至今的UTC時間所經過的秒數。 返回值 返回經過的秒數。 范例 #include main() { time_ttimep; strcuttm *p; time(&timep); printf(“time(): %d \n”,timep); p=localtime(&timep); timep= mktime(p); printf(“time()->localtime()->mktime():%d\n”,timep); } 執行 time():974943297 time()->localtime()->mktime():974943297 設置系統時間 標準C庫中只有獲取系統時間的API,好像還沒有設置系統時間的API,本文將談談如何在linux和windows平臺設置系統時間,最后給出一個與平臺無關的設置系統時間的封閉函數。 Linux下設置系統時間: 1.Linux下設置系統時間的函數有好幾個,先來看看最常用的stime()函數,這個函數只能精確到秒。 #define _SVID_SOURCE #include int stime(time_t *t); 參數說明: t是以秒為單位的時間值,從GMT1970年1月1日0時0分0秒開始計算。 返回值: 成功返回0,錯誤返回-1,errno錯誤碼,EFAULT表示傳遞的參數錯誤,如時間值是無效的值,EPERM表示權限不夠,注意只有root用戶才有修改系統時間的權限。如果要讓普通程序修改系統時間,可以先切換到root用戶操作,修改完成后,再切換到普通用戶,或者用命令chmod+s給執行文件加上root用戶的權限。 2.linux是如何管理時間的? 在系統啟動時,Linux操作系統將時間從CMOS中讀到系統時間變量中,以后修改時間通過修改系統時間實現。為了保持系統時間與CMOS時間的一致性,Linux每隔11分鐘會將系統時間寫入CMOS,同步時間。從這可以看出,獲取系統時間有兩個途徑,一種是從CMOS中讀,一種是從系統中讀,但修改時間卻只有一種,即修改linux系統中的時間,而修改CMOS中的時間是無效的,因為CMOS中的時間會被定時重寫掉。另外還有一點要注意,修改了系統時間并不是馬上生效的,假如你修改了系統時間并馬上關機,再開機的時候,時間還是原來的,因為修改的時間還沒有來得及寫入CMOS中。 3.通過settimeofday()函數來設置系統時間,這個函數設置的精度可以精確到微秒。 #include intsettimeofday(const struct timeval *tv , const struct timezone *tz); struct timeval { time_t tv_sec; suseconds_t tv_usec; }; struct timezone { inttz_minuteswest; inttz_dsttime; }; tz參數為時區,時區結構中tz_dsttime在linux中不支持,應該置為0,通常將參數tz設置為NULL,表示使用當前系統的時區。該函數是glib中的,但在mingw中沒有實現。 該函數返回值與stime()一樣,同樣也需要root權限。 4.設置CMOS時間,其實它是通過RTC(Real-timeclock)設備驅動來完成的,你可以用ioctl()函數來設置時間,當然也可以通過操作/dev/rtc設備文件,在此就不詳細說明了。深圳、廣州、鄭州專業嵌入式實訓,聯系郭老師QQ754634522 二、windows下設置系統時間 1.設置當前時區的時間 #include BOOL SetLocalTime(constSYSTEMTIME* lpSystemTime); typedef struct _SYSTEMTIME{ // st WORD wYear; WORD wMonth; //月份從1開始 WORD wDayOfWeek; //SetLocalTime()不使用這個參數 WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME; 函數成功返回非零,失敗返回零。注意要求調用進程必需有SE_SYSTEMTIME_NAME權限。 2.另外還有一個函數SetSystemTime(),它的參數與SetLocalTime一樣,只不過以UTC時區為基準的。 BOOL SetSystemTime(constSYSTEMTIME* lpSystemTime); 二、 一個封裝的設置系統時間的函數 //設置成功返回true,否則返回false bool set_local_time(struct tm& t) { #ifdef_WIN32 SYSTEMTIME st; memset(&st, 0,sizeof(SYSTEMTIME)); st.wYear = t.tm_year + 1970; //注意structtm結構中的年是從1970年開始的計數 st.wMonth = t.tm_mon + 1; //注意structtm結構中的月份是從0開始的 st.wDay = t.tm_mday; st.wHour = t.tm_hour; st.wMinute = t.tm_min; st.wSecond = t.tm_sec; if(!SetLocalTime(&st)) return true; else return false; #else //將structtm結構時間轉換成GMT時間time_t struct time_t st; st = mktime(&t); if(st==-1) return false; if(!stime(st)) return true; else return false; #endif } 三、linux系統時間函數 1、gettimeofday(取得目前的時間) #include #include intgettimeofday ( struct timeval * tv , struct timezone * tz ) 函數說明 gettimeofday()會把目前的時間有tv所指的結構返回,當地時區的信息則放到tz所指的結構中。 timeval結構定義為: structtimeval{ longtv_sec; longtv_usec; }; timezone結構定義為: structtimezone{ inttz_minuteswest; inttz_dsttime; }; 上述兩個結構都定義在/usr/include/sys/time.h。tz_dsttime所代表的狀態如下 DST_NONE DST_USA DST_AUST DST_WET DST_MET DST_EET DST_CAN DST_GB DST_RUM DST_TUR DST_AUSTALT 返回值 成功則返回0,失敗返回-1,錯誤代碼存于errno。附加說明EFAULT指針tv和tz所指的內存空間超出存取權限。 范例 #include #include main(){ structtimeval tv; structtimezone tz; gettimeofday(&tv , &tz); printf(“tv_sec;%d\n”, tv,.tv_sec) ; printf(“tv_usec;%d\n”,tv.tv_usec); printf(“tz_minuteswest;%d\n”, tz.tz_minuteswest); printf(“tz_dsttime,%d\n”,tz.tz_dsttime); } 執行 tv_sec: 974857339 tv_usec:136996 tz_minuteswest:-540 tz_dsttime:0 2、settimeofday(設置目前時間) #include #include intsettimeofday ( const struct timeval *tv,const struct timezone *tz); 函數說明 settimeofday()會把目前時間設成由tv所指的結構信息,當地時區信息則設成tz所指的結構。詳細的說明請參考gettimeofday()。注意,只有root權限才能使用此函數修改時間。 返回值 成功則返回0,失敗返回-1,錯誤代碼存于errno。 錯誤代碼 EPERM 并非由root權限調用settimeofday(),權限不夠。 EINVAL時區或某個數據是不正確的,無法正確設置時間。 3、clock_gettime(獲取指定時鐘的時間值) #include intclock_gettime( clockid_t clock_id,struct timespec * tp ); 說明:clock_id指定要獲取時間的時鐘,根據Posix的指定可以是以下值: CLOCK_REALTIME Systemwiderealtime clock. CLOCK_MONOTONIC Representsmonotonic time. Cannot be set. CLOCK_PROCESS_CPUTIME_ID Highresolution per-process timer. CLOCK_THREAD_CPUTIME_ID Thread-specifictimer. CLOCK_REALTIME_HR Highresolution version of CLOCK_REALTIME. CLOCK_MONOTONIC_HR Highresolution version of CLOCK_MONOTONIC. structtimespec { time_ttv_sec; long tv_nsec; }; 4、adjtimex(tunekernel clock) #include intadjtimex(struct timex *buf); 說明: Linux uses David L. Mills' clock adjustmentalgorithm (see RFC 1305).The system call adjtimex() reads and optionally setsadjustment parame-ters for this algorithm. It takes a pointer to a timexstructure,updates kernel parameters from field values, and returns the same structure with current kernelvalues. This structure isdeclared as follows: structtimex { intmodes; longoffset; longfreq; longmaxerror; longesterror; intstatus; longconstant; longprecision; longtolerance; structtimeval time; longtick; }; Themodes field determines which parameters, if any, to set. It may contain a bitwise-or combinationof zero or more of the following bits: #defineADJ_OFFSET 0x0001 #defineADJ_FREQUENCY 0x0002 #defineADJ_MAXERROR 0x0004 #defineADJ_ESTERROR 0x0008 #defineADJ_STATUS 0x0010 #defineADJ_TIMECONST 0x0020 #defineADJ_TICK 0x4000 #defineADJ_OFFSET_SINGLESHOT 0x8001 Ordinaryusers are restricted to a zero value for mode. Only the supe-ruser may set anyparameters. RETURNVALUE Onsuccess, adjtimex() returns the clock state: #defineTIME_OK 0 #defineTIME_INS 1 #defineTIME_DEL 2 #defineTIME_OOP 3 #defineTIME_WAIT 4 #defineTIME_BAD 5 Onfailure, adjtimex() returns -1 and sets errno. ERRORS EFAULT bufdoes not point to writable memory. EINVAL Anattempt is made to set buf.offset to a value outside the range -131071 to +131071,or to set buf.status to a value other than those listed above, or to setbuf.tick to a value outside the range 900000/HZ to 1100000/HZ, where HZ is thesystem timer interruptfrequency. EPERM buf.modeis non-zero and the caller does not have sufficient privilege.Under Linux theCAP_SYS_TIME capability is required. CONFORMINGTO adjtimex()is Linux specific and should not be used in programs intended to be portable.See adjtime(3) for a more portable, but less flexible, method of adjusting thesystem clock.更多嵌入式學習詳情聯系郭老師QQ754634522 |