localtime, localtime_r, localtime_s
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <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 オブジェクトを指すポインタ、そうでなければヌルポインタ。 この構造体は gmtime、
localtime および ctime の間で共有されているかもしれず、呼び出しのたびに上書きされるかもしれません。2,3)
buf ポインタのコピー、またはエラー (実行時制約違反または指定された時刻のローカルカレンダー時刻への変換の失敗かもしれません) の場合はヌルポインタ。ノート
関数 localtime はスレッドセーフでないかもしれません。
POSIX は引数が大きすぎるために関数 localtime および localtime_r が失敗した場合は errno を EOVERFLOW に設定することを要求しています。
POSIX は localtime および localtime_r は tzset を呼んだかのように (つまり環境変数 TZ を読み取って) タイムゾーン情報を判定すると規定しています。
Microsoft CRT の localtime_s の実装は引数の順序が逆であり、また errno_t を返すため C 標準と非互換です。
例
Run this code
#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
関連項目
(C11) |
エポックからの経過時間を協定世界時 (UTC) として表したカレンダー時刻に変換します (関数) |
localtime の C++リファレンス
| |