- #include<time.h> //C語言的頭文件
- #include<stdio.h> //C語言的I/O
- void main()
- {
- time_t now; //實例化time_t結構
- struct tm *timenow; //實例化tm結構指針
- time(&now);
- //time函數讀取現在的時間(國際標准時間非北京時間),然后傳值給now
- timenow = localtime(&now);
- //localtime函數把從time取得的時間now換算成你電腦中的時間(就是你設置的地區)
- printf("Local time is %s/n",asctime(timenow));
- //上句中asctime函數把時間轉換成字符,通過printf()函數輸出
- }
注釋:time_t是一個在time.h中定義好的結構體。而tm結構體的原形如下:
- struct tm
- {
- int tm_sec;//seconds 0-61
- int tm_min;//minutes 1-59
- int tm_hour;//hours 0-23
- int tm_mday;//day of the month 1-31
- int tm_mon;//months since jan 0-11
- int tm_year;//years from 1900
- int tm_wday;//days since Sunday, 0-6
- int tm_yday;//days since Jan 1, 0-365
- int tm_isdst;//Daylight Saving time indicator
- };
#include "time.h"
time_t time(time_t *timer);
調用后將當前系統時間與1900年1月1日相差的秒數存入到timer中,timer可看成是一個長整型數
struct tm* localtime(const time_t *timer)
將time()函數調用的結果做為參數傳入到localtime()函數中就能得到當前時間和日期,注意得到的年是和1970的差值,月份是和1月的差值
struct tm是一個結構體,定義如下
- struct tm
- {
- int tm_sec; //當前秒
- int tm_min; //當前分鍾
- int tm_hour; //當前小時
- int tm_mday; //當前在本月中的天,如11月1日,則為1
- int tm_mon; //當前月,范圍是0~11
- int tm_year; //當前年和1900的差值,如2006年則為36
- int tm_wday; //當前在本星期中的天,范圍0~6
- int tm_yday; //當前在本年中的天,范圍0~365
- int tm_isdst; //這個我也不清楚
- }
求當前時間的示例
- int getSystemTime()
- {
- time_t timer;
- struct tm* t_tm;
- time(&timer);
- t_tm = localtime(&timer);
- printf("today is %4d%02d%02d%02d%02d%02d/n", t_tm.tm_year+1900,
- t_tm.tm_mon+1, t_tm.tm_mday, t_tm.tm_hour, t_tm.tm_min, t_tm.tm_sec);
- return 0;
- }
- /************************************************
- 設置操作系統時間
- 參數:*dt數據格式為"2006-4-20 20:30:30"
- 調用方法:
- char *pt="2006-4-20 20:30:30";
- SetSystemTime(pt);
- **************************************************/
- int SetSystemTime(char *dt)
- {
- struct rtc_time tm;
- struct tm _tm;
- struct timeval tv;
- time_t timep;
- sscanf(dt, "%d-%d-%d %d:%d:%d", &tm.tm_year,
- &tm.tm_mon, &tm.tm_mday,&tm.tm_hour,
- &tm.tm_min, &tm.tm_sec);
- _tm.tm_sec = tm.tm_sec;
- _tm.tm_min = tm.tm_min;
- _tm.tm_hour = tm.tm_hour;
- _tm.tm_mday = tm.tm_mday;
- _tm.tm_mon = tm.tm_mon - 1;
- _tm.tm_year = tm.tm_year - 1900;
- timep = mktime(&_tm);
- tv.tv_sec = timep;
- tv.tv_usec = 0;
- if(settimeofday (&tv, (struct timezone *) 0) < 0)
- {
- printf("Set system datatime error!/n");
- return -1;
- }
- return 0;
- }
其他時間的函數和結構還有:
timeval結構
#include <include/linux/time.h>
struct timeval
{
time_t tv_sec;
susecond_t tv_usec; //當前妙內的微妙數
};
tms結構
保存着一個進程及其子進程使用的cpu時間
struct tms
{
clock_t tms_utime;
clock_t tms_stime;
clock_t tms_cutime;
clock_t tms_cstime;
}
timer_struct結構
#include <include/linux/timer.h>
struct timer_struct
{
unsigned long expires; //定時器被激活的時刻
void (*fn)(void); //定時器激活后的處理函數
}
utime函數
更改文件的存取和修改時間
int utime(const char pathname, const struct utimbuf *times) // return value 0 or -1
times 為空指針,存取和修改時間設置為當前時間
struct utimbuf
{
time_t actime;
time_t modtime;
}