該類型定義在頭文件/usr/include/sys/time.h 中:
#define _TIME_T
typedef long time_t;
#endif
函數定義:time_t time(time_t* lpt);
如:time_t time = time(NULL);
由函數gettime0fday()獲取;
struct timeval結構定義爲:
struct timeval
{
long tv_sec;
long tv_usec;
}
讀取struct timeval結構數據的函數說明:
#include <sys/time.h>
int gettimeofday(struct timeval* tv,struct timezone* tz);
該函數會提取系統當前時間,並把時間分爲秒和微秒兩部分填充到結構struct timeval中;同時把當地的時區信
息填充到結構struct timezone中;
返回值:成功則返回0,失敗返回-1,錯誤代碼存於errno。附加說明EFAULT指針tv和tz所指的內存空間超出存
取權限。
struct timezone結構的定義爲:
struct timezone
{
int tz_minuteswest;
int tz_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
{
int tm_sec; /*代表目前秒數,正常範圍爲0-59,但允許至61秒 */
int tm_isdst; /*日光節約時間的旗標DST. [-1/0/1]*/
4、struct timeb結構:它有兩個主要成員,一個是秒,另一個是毫秒;精確度:毫秒(10E-3秒);
由函數ftime()獲取structtimeb結構的時間;其定義如下:
structtimeb
{
time_t time;
unsigned shortmillitm;
short timezone;
short dstflag;
};
#include <sys/timeb.h>
int ftime(struct timeb* tp);
調用成功返回0;調用失敗返回-1;
5、struct timespec結構:它是POSIX.4標準定義的一個時間結構,精確度:納秒(10E-9秒);
由函數gethrestime()或gethrestime_lasttick()獲取當前系統struct timespec結構的時間;其定義如下:
struct timespec
{
time_t tv_sec;
long tv_nsec;
};
typedef struct timespec timespec_t;
該結構定義在頭頭文件 /usr/include/sys/time_impl.h 中;
extern void gethrestime(timespec_t*);
extern void gethrestime_lasttick(timespec_t*);
6、clock_t 類型:由函數clock()獲取;
#include <time.h>
clock_t clock(void);
該函數以微秒的方式返回CPU的時間;
類型 clock_t 定義在頭文件/usr/include/sys/types.h中:
#ifndef _CLOCK_T
#define _CLOCK_T
typedef long clock_t;
#endif
7、Unix對時間單位的定義:
#defineSEC 1 //
秒
#defineMILLISEC 1000 // 毫秒
#defineMICROSEC 1000000 // 微秒
#defineNANOSEC 1000000000 // 納秒
二、具體操作函數
說 明:此函數返回的時間日期未經時區轉換,而是UTC時間。
返回值:返回結構tm代表目前UTC 時間
#include "stdio.h"
#include "time.h"
#include "stdlib.h"
int main(void)
{
time_t t;
struct tm *gmt, *area;
tzset(); /* tzset()設置時區*/
t = time(NULL);
area = localtime(&t);
printf("Local time is: %s", asctime(area));
gmt = gmtime(&t);
printf("GMT is: %s", asctime(gmt));
return 0;
}
的結構體.
程序例1:
需要注意的是年份加上1900,月份加上1。
t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime_r(const time_t *timep, struct tm *result);
一個好的方法是使用gmtime_r和localtime_r,由於使用了用戶分配的內存,這兩個函數是不會出錯的。
而asctime是通過tm結構來生成時間字符串。
功 能:將tm時間結構數據轉換成經過的秒數(日曆時間)。
從公元1970年1月1日0時0分0 秒算起至今的UTC時間所經過的秒數。
這是由它的參數決定的。
最多向strDest中存放maxsize個字符。
格式化命令說明串strDest中各種日期和時間信息的確切表示方法。格式串中的其他字符原樣放進串中。
格式命令列在下面,它們是區分大小寫的。