Linux uses C to get the current time

Source: Internet
Author: User
Tags local time

Linux uses C to get the current time, specifically as follows:

Code (you can change the Clock_gettime to Time (NULL))

12345678910 void getNowTime(){ timespec time; clock_gettime(CLOCK_REALTIME, &time); //获取相对于1970到现在的秒数 tm nowTime; localtime_r(&time.tv_sec, &nowtime); char current[1024]; sprintf(current, "%04d%02d%02d%02d:%02d:%02d", nowTime.tm_year + 1900, nowTime.tm_mon, nowTime.tm_mday,   nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec);}


Clock_gettime ()

The function "Clock_gettime" is a time function based on the Linux C language, which he can use to calculate precision and nanosecond.


123 #include<time.h>int clock_gettime(clockid_t clk_id,structtimespec *tp);


CLK_ID: Retrieves and sets the clk_id specified clock time.

Clock_realtime: System real-time, with the system changes in real time, that is, from the utc1970-1-1 0:0:0 start timing, intermediate time if the system time is changed by the user to other, the corresponding time corresponding change

    • Clock_monotonic: Starting from the moment the system starts, it is not affected by the change of the system time by the user
    • CLOCK_PROCESS_CPUTIME_ID: The time that this process takes to the current code system CPU
    • CLOCK_THREAD_CPUTIME_ID: The time that this thread spends on the current code system CPU
123456789 structtimespec { time_t tv_sec; /* 秒*/ long tv_nsec; /* 纳秒*/};

LocalTime ()

LocalTime is converting the number of seconds from 1970-1-1:00 to the current time system to local time.


Description: The time that this function obtains for the TM structure body is the calendar time.

Usage: struct TM *localtime (const time_t *clock);

Return value: Returns a pointer to the TM structure. The TM struct is a structure defined in time.h for each amount of time (year, month, etc.) that is stored separately.

Example 1:

123456789101112 #include <stdio.h>#include <stddef.h>#include <time.h>int main(void){ time_t timer;//time_t就是long int 类型 struct tm *tblock; timer = time(NULL); tblock = localtime(&timer); printf("Local time is: %s\n", asctime(tblock)); return 0;}

Execution Result:

Local time Is:mon Feb 16 11:29:26 2009

Example 2:

The above example uses the Asctime function, and the following example does not use this function to get the current time of the system. It should be noted that the year plus 1900, the month plus 1.

1234567891011 #include<time.h>#include<stdio.h>int main(){ struct tm *t; time_t tt; time(&tt); t = localtime(&tt); printf("%4d年%02d月%02d日 %02d:%02d:%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); return 0;}

The difference between localtime () and Localtime_r ()

LocalTime ():

12345678910111213141516171819202122232425262728 #include <cstdlib> #include <iostream> #include <time.h> #include <stdio.h>  using namespace std;   int main(int argc, char *argv[]) {  time_t tNow =time(NULL);  time_t tEnd = tNow + 1800;  //注意下面两行的区别  struct tm* ptm = localtime(&tNow);  struct tm* ptmEnd = localtime(&tEnd);   char szTmp[50] = {0};  strftime(szTmp,50,"%H:%M:%S",ptm);  char szEnd[50] = {0};  strftime(szEnd,50,"%H:%M:%S",ptmEnd);     printf("%s /n",szTmp);  printf("%s /n",szEnd);     system("PAUSE");  return EXIT_SUCCESS; }

The final result is:



Inconsistent with the original idea.

Check out the localtime documentation and find this passage:

This structure is statically allocated and GKFX by the functions Gmtime and localtime. Each time either one of these functions are called the content of this structure is overwritten.

That means you can only use the localtime () function once at a time, or it will be rewritten!

The localtime () function need not be reentrant. A function, that is, required to being reentrant is not required to be thread-safe.

therefore localtime () is not reentrant. At the same time LIBC provides a reentrant version of the function Localtime_r ();

Unlike localtime (), the reentrant version is not required to set tzname.

Modify the program: (Localtime_r ())

12345678910111213141516171819202122232425262728293031 #include <cstdlib> #include <iostream> #include <time.h> #include <stdio.h>  using namespace std;  int main(int argc, char *argv[]) {  time_t tNow =time(NULL);  time_t tEnd = tNow + 1800;   //在这里修改程序  //struct tm* ptm = localtime(&tNow);  //struct tm* ptmEnd = localtime(&tEnd);  struct tm ptm = { 0 };  struct tm ptmEnd = { 0 };  localtime_r(&tNow, &ptm);  localtime_r(&tEnd, &ptmEnd);    char szTmp[50] = {0};  strftime(szTmp,50,"%H:%M:%S",&ptm);  char szEnd[50] = {0};  strftime(szEnd,50,"%H:%M:%S",&ptmEnd);  printf("%s /n",szTmp);  printf("%s /n",szEnd);     system("PAUSE");  return EXIT_SUCCESS; }

The final result is:



1234567891011 struct tm {    int tm_sec;  /* 秒 – 取值区间为[0,59] */    int tm_min;  /* 分 - 取值区间为[0,59] */    int tm_hour;  /* 时 - 取值区间为[0,23] */    int tm_mday;  /* 一个月中的日期 - 取值区间为[1,31] */    int tm_mon;  /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */    int tm_year;  /* 年份,其值等于实际年份减去1900 */    int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一 */    int tm_yday; /* 从每年1月1日开始的天数– 取值区间[0,365],其中0代表1月1日 */    int tm_isdst; /* 夏令时标识符,夏令时tm_isdst为正;不实行夏令时tm_isdst为0 */  };

Time function

Returned: 1970-1-1, number of seconds since 00:00:00

Prototype: time_t time (time_t *calptr)

Results can be obtained by return values or by parameters, see example

Header Files <time.h>

return value:

Success: Number of seconds, from 1970-1-1,00:00:00 can be used as integer output or for other functions




123 time_tnow;time(&now);// 等同于now = time(NULL)printf("now time is %d\n", now);

Linux uses C to get the current time

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.