Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C 語言取得當前時間並轉為字串

「印出現在時間」是個很常寫的小功能,每次都要翻一下 time.h 的欄位定義,乾脆留一份可複製的範例。

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

int main()
{
  time_t nowtime = time(NULL);
  tm *now = localtime(&nowtime);
  printf("now: %04d-%02d-%02d %02d:%02d:%02d\nunix time: %ld\n",
   now->tm_year+1900, now->tm_mon+1, now->tm_mday,
   now->tm_hour, now->tm_min, now->tm_sec, (long)nowtime);
  return 0;
}

幾個容易忘的細節:tm_year 是從 1900 起算的偏移量,tm_mon 從 0 開始,所以都要各自加回去。若想要彈性自訂格式而不想逐欄位 printf,可以改用 strftime 搭配 %Y-%m-%d %H:%M:%S 這類格式字串,程式碼會乾淨不少。另外 localtime 回傳的是靜態緩衝區位址,多執行緒環境請改用 localtime_r。

Copyright © Linux教程網 All Rights Reserved