localtime, localtime_r, localtime_s
来自 cppreference.cn
定义于头文件 <time.h> |
||
(1) | ||
(2) | (自 C23 起) | |
(3) | (C11 起) | |
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 对象以存储结果的指针 |
[编辑] 返回值
2,3) 成功时,返回 buf 指针的副本;错误时(可能是运行时约束违例或无法将指定时间转换为本地日历时间)返回空指针。
[编辑] 注意
函数 localtime
可能不是线程安全的。
POSIX 要求如果 localtime
和 localtime_r
因参数过大而失败,则将 errno 设置为 EOVERFLOW。
POSIX 指定 localtime
和 localtime_r
的时区信息由调用 tzset
来确定,后者读取环境变量 TZ。
在 Microsoft CRT 中 localtime_s
的实现与 C 标准不兼容,因为它参数顺序相反且返回 errno_t。
[编辑] 示例
运行此代码
#define __STDC_WANT_LIB_EXT1__ 1 #define _XOPEN_SOURCE // for putenv #include <stdio.h> #include <stdlib.h> // for putenv #include <time.h> 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
[编辑] 参考文献
- C23 标准 (ISO/IEC 9899:2024)
- 7.27.3.4 The localtime function (p: TBD)
- K.3.8.2.4 The localtime_s function (p: TBD)
- C17 标准 (ISO/IEC 9899:2018)
- 7.27.3.4 The localtime function (p: 288)
- K.3.8.2.4 The localtime_s function (p: 455)
- C11 标准 (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 标准 (ISO/IEC 9899:1999)
- 7.23.3.4 The localtime function (p: 343)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.12.3.4 The localtime function
[编辑] 参阅
(C23)(C11) |
将自纪元以来的时间转换为协调世界时 (UTC) 表示的日历时间 (function) |
C++ 文档 关于 localtime
|