gmtime, gmtime_r, gmtime_s
来自cppreference.com
| 在标头 <time.h> 定义
|
||
| |
(1) | |
| |
(2) | (C23 起) |
| |
(3) | (C11 起) |
2) 同 (1),除了函数使用用户为结果提供的存储
buf。3) 同 (1),除了函数使用用户为结果提供的存储
buf,还在运行时检测下列错误,并调用当前安装的约束处理函数:
timer或buf是空指针
- 同所有边界检查函数,
gmtime_s,仅若实现定义__STDC_LIB_EXT1__且用户在包含 <time.h> 前定义__STDC_WANT_LIB_EXT1__为整数常量 1 才保证可用。
参数
| timer | - | 指向要转换的 time_t 对象的指针 |
| buf | - | 指向要存储结果的 struct tm 对象的指针
|
返回值
1) 成功时返回指向静态的内部 struct tm 对象的指针,失败时返回空指针。该结构体可能会为
gmtime 、 localtime 以及 ctime 所共享,并于每次调用时被覆盖。2,3) 成功时返回
buf 指针的副本,错误时返回空指针(可能是一个运行时制约违规或对指定时间到 UTC 的转换失败)。注解
函数 gmtime 可能不是线程安全的。
POSIX 要求 gmtime 与 gmtime_r 函数若因参数过大而失败,则设置 errno 为 EOVERFLOW 。
Microsoft CRT 中 gmtime_s 的实现与 C 标准不兼容,因为它有相反的参数顺序。
示例
运行此代码
#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.3 The gmtime function (第 TBD 页)
- K.3.8.2.3 The gmtime_s function (第 TBD 页)
- C17 标准(ISO/IEC 9899:2018):
- 7.27.3.3 The gmtime function (第 288 页)
- K.3.8.2.3 The gmtime_s function (第 454-455 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.27.3.3 The gmtime function (第 393-394 页)
- K.3.8.2.3 The gmtime_s function (第 626-627 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.23.3.3 The gmtime function (第 343 页)
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.12.3.3 The gmtime function
参阅
(C23)(C11) |
将从纪元开始的时间转换成以本地时间表示的日历时间 (函数) |
gmtime 的 C++ 文档
| |