Time.h

標準Cライブラリ(libc)
一般
  • データ型(英語版)
  • 文字の分類(英語版)
  • 文字列(英語版)
  • 数学(英語版)
  • 標準入出力
  • 日付と時間
  • ローカライゼーション(英語版)
  • メモリ確保(英語版)
  • プロセス管理(英語版)
  • シグナル(英語版)
  • 代替トークン
その他
  • <assert.h(英語版)>
  • <errno.h(英語版)>
  • <setjmp.h(英語版)>
  • <stdarg.h(英語版)>

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エポックからの経過時間。

出典

  1. ^ ISO/IEC 9899:1999 specification. p. 351, § 7.32.2. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf 
  2. ^ open-std.org - Committee Draft -- May 6, 2005 page 355
  3. ^ Markus Kuhn. “Modernized API for ISO C”. cl.cam.ac.uk. 2023年11月30日閲覧。

関連項目

外部リンク

ウィキブックスにtime.h関連の解説書・教科書があります。
  • K&R
  • ANSI C
    • C89
    • C90
  • C99
  • C11
  • C17(英語版)
  • C2x(英語版)
  • Embedded C(英語版)
  • MISRA C
Cの機能
  • 関数
  • ヘッダファイル
  • 演算子
  • 文字列(英語版)
  • 文法(英語版)
  • プリプロセッサ(英語版)
  • データ型(英語版)
  • キーワード
  • フリースタンディング環境
  • 標準Cライブラリの関数
    • ctype.h(英語版)
    • stdio.h
    • math.h(英語版)
    • stdlib.h(英語版)
    • string.h(英語版)
    • time.h
    • stdarg.h(英語版)
    • POSIXライブラリ(英語版)
    標準Cライブラリ
    コンパイラ
    統合開発環境
    派生言語
    関連項目
    • カテゴリ カテゴリ