C語言獲取當前時間
阿新 • • 發佈:2019-02-04
作業系統提供了很多系統呼叫,既方便程式設計師程式設計,又提高了程式的可移植性。在介紹利用系統呼叫獲取當前時間之前,先辨析幾個基本的概念。
API ,系統呼叫 ,封裝例程
- API只是一個函式定義。
- 系統呼叫通過軟中斷向核心發出一個明確的請求。
- Libc庫定義了一些API引用的封裝例程,唯一的目的就是釋出系統呼叫。一般每個系統呼叫對應一個封裝例程。
- API可能提供使用者態的服務,如數學函式。一個簡單的API可能呼叫幾個系統呼叫,不同的API也可能呼叫了同一個系統呼叫。 C庫對time_t, tm的定義
time.h中time_t, tm的定義
- time_t 其實就是long資料型別。
- tm是一個結構體。主要的成員變數是年(相對於1900年的差值),月,日,時,分,秒。
time.h中函式介紹
time_t(time_t *timer);
Parameter: timer
Return Value: Return the time as seconds elapsed since midnight, January 1, 1970, or -1 in the case of an error.
struct tm *localtime( const time_t *timer );
- Return Value: localtime returns a pointer to the structure result. If the value in timer represents a date before midnight, January 1, 1970, localtime returns NULL.
- Parameter: timer Pointer to stored time
獲取時間程式碼示例
#include <stdio.h>
#include <time.h>
int
main(void)
{
time_t tt;
struct tm *t;
tt = time(NULL);
t = localtime(&tt);
printf("time:%d:%d:%d:%d:%d:%d!\n", t->tm_year + 1900, t->tm_mon, t->tm_mday, \
t->tm_hour, t->tm_min, t->tm_sec);
return 0;
}