ちょっと前に、gettimeofday() と localtime() を使って現在の日時を取得する方法を書いた。
実はマイクロ秒が必要ないなら gettimeofday() ではなく time() を使ったほうがシンプルにできる。
sys/time.h ファイルのインクルードも不要になる。
ここに time() を使う方法も書いておく。
次の手順で現在の日時を取得できる。
time()でUNIX時間を取得- UNIX時間を
localtime()で tm 構造体に変換
次のプログラムは現在の日時を yyyy/MM/dd HH:mm:ss 形式で出力する。
#include <stdio.h> #include <time.h> void main() { /* UNIX時間を取得 */ time_t currentTime; time(¤tTime); /* UNIX時間を tm 構造体に変換 */ struct tm *tmptr = localtime(¤tTime); if (tmptr == NULL) { printf("localtime failed\n"); return; } /* tm 構造体の内容を出力(yyyy/MM/dd HH:mm:ss 形式) */ printf("%04d/%02d/%02d %02d:%02d:%02d\n", tmptr->tm_year + 1900, tmptr->tm_mon + 1, tmptr->tm_mday, tmptr->tm_hour, tmptr->tm_min, tmptr->tm_sec); }
time()
time() は、UNIX時間(1900年1月1日午前0時0分0秒(UTC)からの経過秒)を取得する。
#include <time.h> time_t time(time_t *tloc);
UNIX時間は、引数のポインタが指す変数に格納されるほか、戻り値としても返される。
(引数には NULL の指定も可)
もし、時間が取得できなかった場合、((time_t) -1) が返される。
例)次のプログラムはUNIX時間を出力する。
#include <stdio.h> #include <time.h> int main() { time_t currentTime; if ( time(¤tTime) == -1 ) { printf("time failed"); return 1; } printf("UNIX time: %ld\n", currentTime); return 0; }
↓ 実行結果
UNIX time: 1711466460