localtime, localtime_r, localtime_s
来自cppreference.com
| 在标头 <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 对象的的指针
|
返回值
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 实现与 C 标准不兼容,因为它有相反的参数顺序且返回的是 errno_t。
示例
运行此代码
#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // 为 putenv
#include <time.h>
#include <stdio.h>
#include <stdlib.h> // 为 putenv
int main(void)
{
time_t t = time(NULL);
printf("UTC: %s", asctime(gmtime(&t)));
printf("local: %s", asctime(localtime(&t)));
// POSIX 专有
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 (第 TBD 页)
- K.3.8.2.4 The localtime_s function (第 TBD 页)
- C17 标准(ISO/IEC 9899:2018):
- 7.27.3.4 The localtime function (第 288 页)
- K.3.8.2.4 The localtime_s function (第 455 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.27.3.4 The localtime function (第 394 页)
- K.3.8.2.4 The localtime_s function (第 627 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.23.3.4 The localtime function (第 343 页)
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.12.3.4 The localtime function
参阅
(C23)(C11) |
将从纪元开始的时间转换成以协调世界时(UTC)表示的日历时间 (函数) |
localtime 的 C++ 文档
| |