LoginSignup
9
7

More than 5 years have passed since last update.

C言語の時刻・時間を図示してみた

Last updated at Posted at 2019-04-04

C言語には、扱いにくいと個人的には思っている時間関数があります。
扱いにくかろうと、それ以上のモノを作るスキルはないので大人しく従いますが、どうにも覚えにくかったのでつながりを書いてきます。。

Windows編とかクロックとかタイマーとか増やしていくかも?

Linuxはこっち見て

tl;dr(too long didn't read)

time_correlation_diagram.png

C言語標準:time_t型

1970年1月1日0時0分0秒(UTC)からの経過秒数を示す型。
つまり、このままでは日付も時刻も分からない

構造体定義
#include <time.h>
time_t time(time_t *t);

C言語標準の時刻取得関数。
以下の2通りの使い方があります。

time()の記法
time_t current_time;
time(&current_time); // バッファを与えるとそこに入れてくれる
or
time_t current_time = time(NULL); // 戻り値でもOK

C言語標準:構造体struct tm型

より詳細な日付情報が欲しい場合に用いる。
ログに日付出すときに大活躍しました。
Linux Kernel内でもstruct timespecstruct 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) */
    int tm_year;       /* 年 - 1900 */
    int tm_wday;       /* 曜日 (0-6, 日曜 = 0) */
    int tm_yday;       /* 年内通算日 (0-365, 1 月 1 日 = 0) */
    int tm_isdst;      /* 夏時間 */
};

time_t型→文字列型

時刻を文字表現にしたいときに使います。

時刻->文字表記
#include <time.h>
char *ctime(const time_t *timep);  // Thread unsafe
char *ctime_r(const time_t *timep, char *buf); // Thread safe
  • C言語標準ctime()
    内部メモリのポインタを返してしまうため、内部メモリが書き換わると受け取った先も変わってしまうスレッドアンセーフな問題を持ります。
  • POSIX限定ctime_r()
    ユーザー側に出力バッファを要求しているため、内部で書き換わったとしても値は保障されます。

time_t型→struct tm型

わざわざtime_t型から変換するのも手間だし、現在時刻のstruct tmを返す関数ぐらいあってもいいじゃんと思うのは私だけですか?
きっと、私が知らないだけですよね。

変換関数
#include <time.h>
// GMT
struct tm *gmtime(const time_t *timep); // Thread unsafe
struct tm *gmtime_r(const time_t *timep, struct tm *result); // Thread safe
// 地域時間
struct tm *localtime(const time_t *timep); // Thread unsafe
struct tm *localtime_r(const time_t *timep, struct tm *result);  // Thread safe

struct tm型→文字列型

変換関数
#include <stdio.h>
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

出力する場合はprintf関数にバラバラに突っ込んでもいいかも。

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7