名前空間
変種
操作

localtime, localtime_r, localtime_s

提供: cppreference.com
< c‎ | chrono
ヘッダ <time.h> で定義
struct tm *localtime  ( const time_t *timer );
(1)
struct tm *localtime_r( const time_t *timer, struct tm *buf );
(2) (C2x以上)
struct tm *localtime_s( const time_t *restrict timer, struct tm *restrict buf );
(3) (C11以上)
1) 指定されたエポックからの経過時間 (timer の指す time_t の値) を現地時間で表される struct tm 形式のカレンダー時刻に変換します。 結果は静的記憶域に格納され、その静的記憶域を指すポインタが返されます。
2) (1) と同じですが、この関数は結果のためにユーザ提供の記憶域 buf を使用します。
3) (1) と同じですが、この関数は結果のためにユーザ提供の記憶域 buf を使用し、以下のエラーが実行時に検出され、現在設定されている制約ハンドラ関数を呼びます。
  • timer または buf がヌルポインタ。
すべての境界チェック付き関数と同様に、 localtime_s__STDC_LIB_EXT1__ が処理系によって定義されていて、 <time.h> をインクルードする前にユーザが __STDC_WANT_LIB_EXT1__ を整数定数 1 に定義した場合にのみ、利用可能であることが保証されます。

目次

[編集] 引数

timer - 変換する time_t オブジェクトを指すポインタ
buf - 結果を格納する struct tm オブジェクトを指すポインタ

[編集] 戻り値

1) 成功した場合は静的な内部の tm オブジェクトを指すポインタ、そうでなければヌルポインタ。 この構造体は gmtimelocaltime および ctime の間で共有されているかもしれず、呼び出しのたびに上書きされるかもしれません。
2,3) buf ポインタのコピー、またはエラー (実行時制約違反または指定された時刻のローカルカレンダー時刻への変換の失敗かもしれません) の場合はヌルポインタ。

[編集] ノート

関数 localtime はスレッドセーフでないかもしれません。

POSIX は引数が大きすぎるために関数 localtime および localtime_r が失敗した場合は errnoEOVERFLOW に設定することを要求しています。

POSIXlocaltime および localtime_rtzset を呼んだかのように (つまり環境変数 TZ を読み取って) タイムゾーン情報を判定すると規定しています。

Microsoft CRTlocaltime_s の実装は引数の順序が逆であり、また errno_t を返すため C 標準と非互換です。

[編集]

#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // for putenv
#include <time.h>
#include <stdio.h>
#include <stdlib.h>   // for putenv
 
int main(void)
{
    time_t t = time(NULL);
    printf("UTC:       %s", asctime(gmtime(&t)));
    printf("local:     %s", asctime(localtime(&t)));
    // POSIX-specific
    putenv("TZ=Asia/Singapore");
    printf("Singapore: %s", asctime(localtime(&t)));
 
#ifdef __STDC_LIB_EXT1__
    struct tm buf;
    char str[26];
    asctime_s(str,sizeof str,gmtime_s(&t, &buf));
    printf("UTC:   %s", str);
    asctime_s(str,sizeof str,localtime_s(&t, &buf));
    printf("local: %s", str);
#endif
}

出力例:

UTC:       Fri Sep 15 14:22:05 2017
local:     Fri Sep 15 14:22:05 2017
Singapore: Fri Sep 15 22:22:05 2017
UTC:   Fri Sep 15 14:22:05 2017
local: Fri Sep 15 14:22:05 2017


[編集] 参考文献

  • C11 standard (ISO/IEC 9899:2011):
  • 7.27.3.4 The localtime function (p: 394)
  • K.3.8.2.4 The localtime_s function (p: 627)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.23.3.4 The localtime function (p: 343)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.12.3.4 The localtime function

[編集] 関連項目

エポックからの経過時間を協定世界時 (UTC) として表したカレンダー時刻に変換します
(関数) [edit]
localtimeC++リファレンス