命名空间
变体
操作

gmtime, gmtime_r, gmtime_s

来自 cppreference.cn
< c‎ | chrono
定义于头文件 <time.h>
struct tm* gmtime  ( const time_t* timer );
(1)
struct tm* gmtime_r( const time_t* timer, struct tm* buf );
(2) (C23 起)
struct tm* gmtime_s( const time_t* restrict timer, struct tm* restrict buf );
(3) (C11 起)
1) 将给定的 epoch 时间(由 timer 指向的 time_t 值)转换为日历时间,以协调世界时 (UTC) 表示,格式为 struct tm。结果存储在静态存储中,并返回指向该静态存储的指针。
2)(1) 相同,但此函数使用用户提供的存储 buf 来存储结果。
3)(1) 相同,但此函数使用用户提供的存储 buf 来存储结果,并且在运行时检测到以下错误并调用当前安装的 约束处理函数
  • timerbuf 是空指针
与所有边界检查函数一样,只有当实现定义了 __STDC_LIB_EXT1__ 并且用户在包含 <time.h> 之前将 __STDC_WANT_LIB_EXT1__ 定义为整数常量 1 时,才能保证 gmtime_s 可用。

目录

[编辑] 参数

timer - 要转换的 time_t 对象的指针
buf - 用于存储结果的 struct tm 对象的指针

[编辑] 返回值

1) 成功时,指向静态内部 tm 对象的指针;否则,为空指针。该结构可能在 gmtimelocaltimectime 之间共享,并且可能在每次调用时被覆盖。
2,3) buf 指针的副本;如果发生错误(可能是运行时约束冲突或未能将指定时间转换为 UTC),则为空指针。

[编辑] 注意

gmtime 可能不是线程安全的。

POSIX 要求 gmtimegmtime_r 在因参数过大而失败时将 errno 设置为 EOVERFLOW

Microsoft CRTgmtime_s 的实现与 C 标准不兼容,因为它颠倒了参数顺序。

[编辑] 示例

#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.3 The gmtime function (p: TBD)
  • K.3.8.2.3 The gmtime_s function (p: TBD)
  • C17 标准 (ISO/IEC 9899:2018)
  • 7.27.3.3 The gmtime function (p: 288)
  • K.3.8.2.3 The gmtime_s function (p: 454-455)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.27.3.3 The gmtime function (p: 393-394)
  • K.3.8.2.3 The gmtime_s function (p: 626-627)
  • C99 标准 (ISO/IEC 9899:1999)
  • 7.23.3.3 The gmtime function (p: 343)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 4.12.3.3 The gmtime function

[编辑] 参见

将 epoch 时间转换为表示为本地时间的日历时间
(函数) [编辑]
C++ 文档 关于 gmtime