37 - gmtime()函数

1 函数原型

gmtime():时间类型转换,函数原型如下:

struct tm * gmtime (const time_t * timer);

ctime库描述如下:

1. Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone).
2. For a local time alternative, see localtime.
  1. 协调世界时(UTC)
    (1)全称是Coordinated Universal Time(协调世界时),也称为世界统一时间、世界标准时间或国际协调时间;
    (2)是一种基于原子钟的时间标准,不以任何特定国家或地区的夏令时(DST)或标准时间为基准,旨在提供一个全球统一且高度精确的时间测量方式;
    (3)通常表示为24小时制,例如12:00 UTC(正午),18:00 UTC(下午6点),或者02:00 UTC(凌晨2点)等;
    (4)通常转换为当地的时区时间,例如,在中国,UTC时间通常会转换为北京时间(CST,China Standard Time),即UTC+8,来表示当地的时间;
  2. gmtime()函数:
    (1)用于将time_t类型的时间值转换为协调世界时(UTC)表示的struct tm类型的时间结构;
    (2)time_t是一个简单的数值类型,通常表示自1970年1月1日00:00:00 UTC 起经过的秒数;它是一种线性表示方式,适合进行时间的计算和比较;
    (3)struct tm是一个结构体,包含了时间的多个组成部分(如年、月、日、小时、分钟、秒等),这种表示方式更直观,便于显示和处理人类可读的日期和时间信息,通常包含以下成员:
struct tm {
    int tm_sec;   // 秒,范围从 0 到 60
    int tm_min;   // 分,范围从 0 到 59
    int tm_hour;  // 小时,范围从 0 到 23
    int tm_mday;  // 一个月中的第几天,范围从 1 到 31
    int tm_mon;   // 月,范围从 0 到 11
    int tm_year;  // 从 1900 年起的年数
    int tm_wday;  // 一周中的第几天,范围从 0 到 6(0 是星期日)
    int tm_yday;  // 一年中的第几天,范围从 0 到 365
    int tm_isdst; // 夏令时标志
};

2 参数

gmtime()函数只有一个参数timer:

  1. 参数timer是一个指向time_t类型对象的指针,类型为time_t*;timer指向的对象包含要转换的时间值。

ctime库描述如下:

timer
1. Pointer to an object of type time_t that contains a time value.
2. time_t is an alias of a fundamental arithmetic type capable of representing times as returned by function time.

3 返回值

gmtime()函数的返回值类型为struct tm*类型:

  1. 转换成功,返回一个指向静态时间结构的指针,该结构包含了转换后的UTC时间的各个组成部分;
  2. 转换失败,返回NULL。

ctime库描述如下:

1. A pointer to a tm structure with its members filled with the values that correspond to the UTC time representation of timer.
2. The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime.

4 示例

示例代码如下所示:

int main() {
   //
   time_t rawtime = 0;
   struct tm* timeinfo = NULL;
   // 获取当前时间
   time(&rawtime);
   // 将时间转换为UTC时间
   timeinfo = gmtime(&rawtime);
   // 输出结果
   printf("UTC时间 : %d-%02d-%02d %02d:%02d:%02d\n",
      timeinfo->tm_year + 1900,
      timeinfo->tm_mon + 1,
      timeinfo->tm_mday,
      timeinfo->tm_hour,
      timeinfo->tm_min,
      timeinfo->tm_sec);
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值