Linux C編程:獲取當前的系統時間

Linux C編程:獲取當前的系統時間

   獲取當前的系統時間是挺有用的,比如說在進行軟件調試,或者是軟件運行需要獲取當前的時間用於運行日誌的編寫。在Linux中與系統時間相關的函數以及數據類型定義在系統的頭文件<time.h>中,在進行獲取系統時間的程序的編寫的時候主要運用到以下幾個函數:

函數名 註釋
time() 該函數返回的結果是從1970年1月1日0時0分0秒(一般是)到當前時間的秒數。
localtime() 該函數可將time()返回的time_t類型數據轉化爲當前系統的真實時間,並將該轉化結果返回。
strftime() 該函數用於根據區域設置格式化本地時間/日期進行時間格式化,或者說格式化一個時間字符串

   在使用strftime時間格式化函數所涉及的相關參數的含義如下:

參數 含義
%F 將時間格式化爲年-月-日
%T 將時間格式化爲顯示時分秒:hh:mm:ss
%Y 將時間格式化爲帶世紀部分的十制年份
%m 將時間格式化爲十進制表示的月份
%d 將時間格式化爲十進制的每月中的第幾天
%H 將時間格式化爲24小時制的小時
%M 將時間格式化爲十進制表示的分鐘數
%S 將時間格式化爲十進制表示的秒數

更多參數的解析可參考度娘百科:strftime的介紹

   定義時間變量相關的數據類型釋義:

數據類型 含義
time_t 在C中,time_t是表示一個長整型數據,用於表示從1970年1月1日0時0分0秒(一般是)到當前時間的秒數

  讓我們找找該頭文件的源文件中的相關定義吧,首先看看<time.h>頭文件在哪,使用whereis 命令進行文件的查找:

whereis time.h

   結果如下:
時間在哪
   在該頭文件中,結構體 tm中包含年月日時分秒等有關時間的基本的信息。

/* Used by other time functions.  */
struct tm
{
  int tm_sec;			/* Seconds.	[0-60] (1 leap second) */
  int tm_min;			/* Minutes.	[0-59] */
  int tm_hour;			/* Hours.	[0-23] */
  int tm_mday;			/* Day.		[1-31] */
  int tm_mon;			/* Month.	[0-11] */
  int tm_year;			/* Year	- 1900.  */
  int tm_wday;			/* Day of week.	[0-6] */
  int tm_yday;			/* Days in year.[0-365]	*/
  int tm_isdst;			/* DST.		[-1/0/1]*/

# ifdef	__USE_MISC
  long int tm_gmtoff;		/* Seconds east of UTC.  */
  const char *tm_zone;		/* Timezone abbreviation.  */
# else
  long int __tm_gmtoff;		/* Seconds east of UTC.  */
  const char *__tm_zone;	/* Timezone abbreviation.  */
# endif
};

  實際應用相關函數進行編程,實現在Linux中獲取當前的系統時間,並以YYYY-MM-dd hh:mm:ss 的格式進行輸出。
實驗開始了

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

char* getNowtime(void) 
{
	static char s[30]={0};
    char YMD[15] = {0};
    char HMS[10] = {0};
    time_t current_time;
    struct tm* now_time;

    char *cur_time = (char *)malloc(21*sizeof(char));
    time(&current_time);
    now_time = localtime(&current_time);

    strftime(YMD, sizeof(YMD), "%F ", now_time);
    strftime(HMS, sizeof(HMS), "%T", now_time);
    
    strncat(cur_time, YMD, 11);
    strncat(cur_time, HMS, 8);

    printf("\nCurrent time: %s\n\n", cur_time);
	memcpy(s, cur_time, strlen(cur_time)+1);
    free(cur_time);

    cur_time = NULL;

    return s;
}


int main(void)
{
	getNowtime();

	return 0;
}
  

編譯之後的運行結果如下圖所示:
運行時間

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章