您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

如何獲取系統當前時間:time.h 中的三個關鍵函數

編輯:iOS 相關資訊

獲取系統時間是 C 語言里最基礎的操作之一,需要的頭文件只有一個:

#include <time.h>

一、最簡示例

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

int main() {
    time_t timep;   // time_t 本質上是 long int

    time(&timep);   // 把當前時間存入 timep

    // 轉為本地時間可讀字符串並打印
    printf("%s", asctime(localtime(&timep)));

    return 0;
}

二、三個核心函數

time()

time_t time(time_t *t);

返回從 1970 年 1 月 1 日 00:00:00(Unix 紀元)到現在所經過的秒數。如果參數非空,同時把結果寫入該地址。

localtime()

struct tm *localtime(const time_t *clock);

把秒數轉換為本地時區的日期時間結構。與它對應的 gmtime() 則返回未經時區變換的 UTC 時間 —— 這是兩者唯一的差別,也是最容易混淆的地方。返回值是一個指向 struct tm 的指針。

asctime()

char *asctime(const struct tm *timeptr);

把 tm 結構中的信息轉換成人類可讀的字符串形式,例如 Mon Aug 26 15:32:47 2026\n。注意返回的字符串末尾自帶換行符。

三、struct tm 的構成

time.h 中定義的 tm 結構用於分別存儲時間的各個分量:

struct tm {
    int tm_sec;    // 秒    0-60
    int tm_min;    // 分    0-59
    int tm_hour;   // 時    0-23
    int tm_mday;   // 日    1-31
    int tm_mon;    // 月    0-11(注意從 0 開始)
    int tm_year;   // 年    從 1900 起算
    int tm_wday;   // 星期  0-6
    int tm_yday;   // 年内第几天 0-365
    int tm_isdst;  // 夏令時標誌
};

兩個特別容易出錯的字段:tm_mon 從 0 開始計數,所以八月是 7;tm_year 是與 1900 的差值,2026 年要寫 126。直接 printf 這些字段時務必留意。

四、更完整的示例

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

int main() {
    time_t timep;
    struct tm *block;

    timep = time(NULL);   // 返回與 1970-01-01 00:00:00 相差的秒數
    printf("%ld\n", timep);

    block = localtime(&timep);          // 轉換為本地時間結構
    printf("%s", asctime(block));       // 再轉為可讀字符串輸出

    // 也可以按需格式化
    printf("%04d-%02d-%02d %02d:%02d:%02d\n",
           block->tm_year + 1900, block->tm_mon + 1, block->tm_mday,
           block->tm_hour, block->tm_min, block->tm_sec);

    return 0;
}

如果希望輸出格式完全可控,strftime() 比 asctime() 靈活得多,它支持自定義格式串。

五、一點注意事項

localtime() 與 asctime() 返回的都是指向內部靜態緩衝區的指針,並非新分配的內存。這意味著兩件事:一是不要 free 它們;二是在多線程環境中直接調用存在數據競爭風險,此時應改用 localtime_r() 與 ctime_r() 這組可重入版本。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved