time.h

出典: フリー百科事典『ウィキペディア(Wikipedia)』

time.hは、日付と時間を操作するための実装を提供するC言語標準ライブラリヘッダファイルである。time.hでは、システム時刻の取得、日付形式の変換、書式設定された文字列として出力する機能に対応している[1]

機能の概要[編集]

C言語の日付と時間の操作に関する機能は、time.hヘッダファイル[注釈 1]で定義されている。

識別子 説明
時間操作 difftime 2つのtime_t型の値の秒単位の差を計算する。
time 現在のシステム時刻を秒数を表すtime_t型の値として返す[注釈 2]。エポックの値はオペレーティングシステムよって異なり、1900年と1970年がよく使われる。RFC 868を参照。
clock プロセスに関連付けられたCPU時間を返す。
timespec_get(C11) 指定されたベース時間に基づいたカレンダー時間を返す。
形式変換 asctime struct tm型のオブジェクトを文字列表現に変換する(非推奨)。
ctime time_t型の値を文字列表現に変換する。
strftime struct tm型のオブジェクトを指定された書式設定に基づいた文字列表現に変換する。
strptime struct tm時間情報を含んだ文字列をstruct tm型に変換する。
wcsftime struct tm型のオブジェクトを指定された書式設定に基づいたワイド文字列表現に変換する。
gmtime time_t型の値を協定世界時として表現されるカレンダー時間に変換する[2]
localtime time_t型の値を現地時間として表現されるカレンダー時間に変換する。
mktime カレンダー時間をtime_t型の値に変換する。
定数 CLOCKS_PER_SEC 1秒あたりのCPU時間。
TIME_UTC 協定世界時のためのベース時間。
データ型 struct tm カレンダー時間の各要素を表す。
time_t 算術型として定義されている時間型[注釈 3]
clock_t CPU時間を表す。
timespec 秒単位とナノ秒単位の時間を表す。

timespec型と関連する型は、当初は様々なベース時間を提供するためにMarkus Kuhnによって提案されたが、TIME_UTCのみが受け入れられた[3]。ただし、この機能は2020年にC++std::chronoに追加された。

[編集]

以下のC言語のコードは、現在時間を標準出力に出力する。

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

int main(void)
{
    time_t current_time;
    char* c_time_string;

    /* Obtain current time. */
    current_time = time(NULL);

    if (current_time == ((time_t)-1))
    {
        (void) fprintf(stderr, "Failure to obtain the current time.\n");
        exit(EXIT_FAILURE);
    }

    /* Convert to local time format. */
    c_time_string = ctime(&current_time);

    if (c_time_string == NULL)
    {
        (void) fprintf(stderr, "Failure to convert the current time.\n");
        exit(EXIT_FAILURE);
    }

    /* Print to stdout. ctime() has already added a terminating newline character. */
    (void) printf("Current time is %s", c_time_string);
    exit(EXIT_SUCCESS);
}

出力:

Current time is Thu Sep 15 21:18:23 2016

脚注[編集]

注釈[編集]

  1. ^ C++ではctimeヘッダ。
  2. ^ これは通常はエポック英語版からの経過時間であり、一般的にはUNIXエポックである。
  3. ^ 通常はUNIXエポックからの経過時間。

出典[編集]

関連項目[編集]

外部リンク[編集]