gettimeofday()函式的使用方法

1.函式原型

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);

2.說明

gettimeofday()會把目前的時間用tv 結構體返回,當地時區的資訊則放到tz所指的結構中

3.結構體

struct  timeval{

long  tv_sec;/*秒*/

long  tv_usec;/*微妙*/

};

struct  timezone{

int tz_minuteswest; /*和greenwich 時間差了多少分鐘*/

int tz_dsttime; /*DST的校正*/

}

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#define SIZE_OF_DATETIME 20
int sysUsecTime(char *pTime)
{
struct timeval tv;
struct timezone tz;
struct tm *p;
gettimeofday(&tv, &tz);
p = localtime(&tv.tv_sec);
sprintf(pTime,"%04d%02d%02d%02d%02d%02d%06ld",1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, tv.tv_usec);
return 0;
}
int main ()
{
char strusecTime[SIZE_OF_DATETIME+1];
sysUsecTime(strusecTime);
printf("%s\n",strusecTime);
}