当前位置: C语言 -- 标准库 -- <time.h> -- gmtime_r

gmtime_r函数


概要:
#include <time.h>
struct tm *gmtime_r(const time_t *timer, struct tm *buf);

描述:

该函数将参数timer指向的日历时间转换为以UTC时间表示的分解时间(broken-down time)。

gmtime_r函数和gmtime函数功能基本相同,不同之处在于:gmtime_r函数将转换结果存入参数buf指向的缓冲区,并返回该指针。gmtime_r函数不受数据竞争的影响,除非在多线程执行中时间或者日历发生了改变。


参数:
const time_t *timer

参数为指向const time_t类型对象的指针。

struct tm *buf

参数为指向struct tm类型对象的指针。


返回值:

函数返回指向分解时间的指针;如果指定的时间不能转换为UTC时间,函数返回空指针。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
/*函数gmtime_r范例*/

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t currentTime;
    time(&currentTime);
    struct tm buf;
    
    /*本地时间。*/
    printf("Beijing Time: %s\n", asctime(localtime(&currentTime)));

    /*UTC时间。*/
    printf("%4cUTC Time: %s", ' ', asctime(gmtime_r(&currentTime, &buf)));
    
    return 0;
}


输出:

Beijing Time: Tue Sep 22 10:53:43 2026

    UTC Time: Tue Sep 22 02:53:43 2026


相关内容:
localtime_r 将time_t类型日历时间转换为本地时间表示的struct tm类型分解时间的函数。
gmtime 将time_t类型日历时间转换为UTC时间表示的struct tm类型分解时间的函数。
time_t 表示日历时间的实数类型。
struct tm 表示分解时间的结构类型。


主要参考资料:

1、ISO/IEC 9899:2024