C 標準庫 – <time.h>

C 標準庫 - <time.h>

簡介

time.h 標頭檔案定義了四個變數型別、兩個巨集和各種操作日期和時間的函式。

庫變數

下面是標頭檔案 time.h 中定義的變數型別:

序號變數 & 描述
1size_t
是無符號整數型別,它是 sizeof 關鍵字的結果。
2clock_t
這是一個適合儲存處理器時間的型別。
3time_t is
這是一個適合儲存日曆時間型別。
4struct tm
這是一個用來儲存時間和日期的結構。

tm 結構的定義如下:

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 到 11        */
   int tm_year;        /* 自 1900 年起的年數        */
   int tm_wday;        /* 一週中的第幾天,範圍從 0 到 6    */
   int tm_yday;        /* 一年中的第幾天,範圍從 0 到 365    */
   int tm_isdst;       /* 夏令時                */
};

庫巨集

下面是標頭檔案 time.h 中定義的巨集:

序號巨集 & 描述
1NULL
這個巨集是一個空指標常量的值。
2CLOCKS_PER_SEC
這個巨集表示每秒的處理器時鐘個數。

庫函式

下面是標頭檔案 time.h 中定義的函式:

序號函式 & 描述
1char *asctime(const struct tm *timeptr)
返回一個指向字串的指標,它代表了結構 timeptr 的日期和時間。
2clock_t clock(void)
返回程式執行起(一般為程式的開頭),處理器時鐘所使用的時間。
3char *ctime(const time_t *timer)
返回一個表示當地時間的字串,當地時間是基於引數 timer。
4double difftime(time_t time1, time_t time2)
返回 time1 和 time2 之間相差的秒數 (time1-time2)。
5struct tm *gmtime(const time_t *timer)
timer 的值被分解為 tm 結構,並用協調世界時(UTC)也被稱為格林尼治標準時間(GMT)表示。
6struct tm *localtime(const time_t *timer)
timer 的值被分解為 tm 結構,並用本地時區表示。
7time_t mktime(struct tm *timeptr)
把 timeptr 所指向的結構轉換為一個依據本地時區的 time_t 值。
8size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
根據 format 中定義的格式化規則,格式化結構 timeptr 表示的時間,並把它儲存在 str 中。
9time_t time(time_t *timer)
計算當前日曆時間,並把它編碼成 time_t 格式。