Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 區別 gmtime 與 localtime 函數用法(含 C 程式範例與執行結果)

編輯:關於 Linux

C 語言時間處理中,gmtime() 與 localtime() 均將 time_t 轉換為 struct tm,但時區處理不同。本文提供完整 C 程式範例、編譯執行結果與核心差異解析,幫助開發者正確選用。

核心差異

  • gmtime():轉換為 UTC(世界協調時間,時區 +0),不考慮本地時區設定。
  • localtime():轉換為 本地時區時間,依據系統 TZ 環境變數或 /etc/localtime 設定。

注意:嵌入式裝置若未正確配置時區,兩者輸出可能相同(皆為 UTC)。

C 程式範例

#include 
#include 

int main(int argc, char **argv) {
    time_t tmpcal_ptr = 0;
    struct tm *tmp_ptr = NULL;

    tmpcal_ptr = time(NULL);
    printf("tmpcal_ptr=%ld\n", tmpcal_ptr);

    tmp_ptr = gmtime(&tmpcal_ptr);
    printf("after gmtime, the time is:\n%d:%d:%d\n",
           tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);

    tmp_ptr = localtime(&tmpcal_ptr);
    printf("after localtime, the time is:\n%d:%d:%d\n",
           tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);

    return 0;
}

編譯與執行

gcc time_test.c -o time_test
./time_test

執行結果範例(假設系統時區為 CST,UTC+8)

tmpcal_ptr=1359123456
after gmtime, the time is:
3:37:36
after localtime, the time is:
11:37:36

可見 localtime 比 gmtime 多 8 小時(CST = UTC+8)。

gmtime localtime 執行結果截圖

實務建議

  • 日誌記錄、資料庫儲存、跨系統傳輸:統一使用 UTC(gmtime),避免時區混淆。
  • 使用者介面顯示、本地排程:使用 localtime 符合用戶習慣。
  • 嵌入式開發:務必確認 /etc/localtime 或 TZ 正確,否則 localtime 會回傳錯誤時間。
  • C++11 以降推薦使用 <chrono> 與 std::put_time,型別安全且支援時區資料庫(C++20 std::chrono::zoned_time)。
Copyright © Windows教程網 All Rights Reserved