The C language's method of obtaining the exact time of the Linux system

  • 2020-05-27 06:48:51
  • OfStack

How to use the gettimeofday() function

1. Function prototype


#include <sys/time.h>

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

2. Show

gettimeofday() returns the current time using the tv structure, and the local time zone information is placed into the structure referred to by tz

3. The structure of the body


struct timeval{

 

    long tv_sec;/* seconds */

    long tv_usec;/* subtle */

} ; 

struct timezone{

    int tz_minuteswest; /* and greenwich  How many minutes is the delay */

    int tz_dsttime; /*DST The correction */

}

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#define SIZE_OF_DATETIME 20
void sysUsecTime(char *pTime)
{
 struct timeval tv;
 struct timezone tz;
 int i=0;
 struct tm   *p;
 char sys_time[SIZE_OF_DATETIME+1]="";

 gettimeofday(&tv, &tz);
 p = localtime(&tv.tv_sec);
 sprintf(sys_time,"%d%d%d%d%d%d%ld",1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, tv.tv_usec);
 printf("strlen(sys_time)=[%d]\n",strlen(sys_time));
 printf("sys_time=[%s]\n",sys_time);
  /*  The maximum length of time is:   years  4 A,   month  2 position   ,,,  2 position   When,  2 position   ,  2 position   Second,  2 position   ms  6 position  = 20 position  */ 
 /*  Not enough length to the end of the complement 0 */

 for ( i=strlen(sys_time);i<SIZE_OF_DATETIME;i++)
 {
  sys_time[i]='0'; 
 }
 sys_time[SIZE_OF_DATETIME]='\0';
 
 strcpy(pTime,sys_time);
}

int main(void)
{
 char strusecTime[SIZE_OF_DATETIME+1];
 sysUsecTime(strusecTime);
 printf("%s\n",strusecTime);
 return 0;
}

Related articles: