gmtime() 轉換為 UTC (GMT) 標準時間(0 時區),localtime() 則依系統時區設定轉換為本地時間。嵌入式裝置若未正確設定時區(/etc/localtime、TZ 環境變數),兩者輸出可能相同。本文提供完整 C 程式碼驗證差異。
#include
#include
int main(int argc, char **argv) {
time_t tmpcal_ptr = time(NULL);
struct tm *tmp_ptr;
printf("tmpcal_ptr=%ld\n", tmpcal_ptr);
tmp_ptr = gmtime(&tmpcal_ptr);
printf("after gmtime, the time is: %02d:%02d:%02d\n",
tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);
tmp_ptr = localtime(&tmpcal_ptr);
printf("after localtime, the time is: %02d:%02d:%02d\n",
tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);
return 0;
}
tmpcal_ptr=1363842000
after gmtime, the time is: 06:00:00
after localtime, the time is: 14:00:00
# 差異 8 小時 = CST (UTC+8)

/usr/share/zoneinfo/Asia/Shanghai 缺失或未連結至 /etc/localtime。TZ 環境變數(export TZ=CST-8)。tzdata 套件已安裝且 /etc/localtime 指向正確區域檔。gmtime/timegm),顯示層再用 localtime 轉換。std::chrono (C++11) 或 date.h (Howard Hinnant) 避免時區陷阱。