Back to Blog

Methods to Get System Time in Linux

#Linux#Struct#Language#C

The localtime function can be used to obtain the year, month, day, hour, minute, and second values separately.

  C language implementation methods for obtaining system time in Linux:

  1. The localtime function can be used to obtain the year, month, day, hour, minute, and second values separately.

  ```c   #include <time.h> //C language header file   #include <stdio.h> //C language I/O

  void main ()   {   time_t now; // Instantiate time_t structure   struct tm *timenow; // Instantiate tm structure pointer   time(&now);   // The time function reads the current time (International Standard Time, not Beijing time) and passes the value to now   timenow = localtime(&now);   // The localtime function converts the time 'now' obtained from time() into the time on your computer (i.e., your configured region)   printf(" Local time is %s ",asctime(timenow));   // In the above line, the asctime function converts the time to a string and outputs it via printf()   }   ```

  Note: time_t is a structure defined in time.h. The prototype of the tm structure is as follows:

  c   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   };   

  2. For certain requirements needing higher precision, Linux provides gettimeofday().

  ```c   #include <sys/time.h>   #include <stdio.h>   #include <unistd.h>

  int main(int argc, char **argv)   {   struct tim start,stop,diff;   gettimeofday(&start,0);   // Do what you need to do...   gettimeofday(&stop,0);   tim_subtract(&diff,&start,&stop);   printf("Total time taken: %d milliseconds ",diff.tv_usec);   }

  int tim_subtract(struct tim *result, struct tim *x, struct tim *y)   {   int nsec;   if ( x->tv_sec > y->tv_sec )   return -1;   if ((x->tv_sec==y->tv_sec) && (x->tv_usec>y->tv_usec))   return -1;   result->tv_sec = ( y->tv_sec-x->tv_sec ); result->tv_usec = ( y->tv_usec-x->tv_usec );   if (result->tv_usec<0)   {   result->tv_sec--;   result->tv_usec+=1000000;   }   return 0;   }   ```