【C/C++时间系列】通过gmtime()函数将时间戳转换成GMT时间

【GMT】Greenwich Mean Time
格林尼治标准时间的正午是指当太阳横穿格林尼治子午线时(也就是在格林尼治时)的时间。
地球每天的自转是有些不规则的,而且正在缓慢减速。所以,格林尼治时间已经不再被作为标准时间使用。现在的标准时间──世界标准时间(UTC)

【UTC】世界标准时间
法文“Temps Universel Cordonné”缩写则为“TUC”
英文“Coordinated Universal Time”缩写为“CUT”
国际电信联盟折中的方案为  UTC(Universal Time Coordinated)


北京时间=UTC+8=GMT+8

#############

【gmtime()】

函数模型在time.h中

/* Return the `struct tm' representation of *TIMER
   in Universal Coordinated Time (aka Greenwich Mean Time).  */
extern struct tm *gmtime (__const time_t *__timer) __THROW;

函数的参数是一个指向时间戳time_t类型的指针,返回struct tm 类型的分解时间,即UTC时间。分解时间介绍点这里

【gmtime_r()】

gmtime()函数的另一个版本,可以把时间戳保存在 tm类型的__restrict __tp中。  


/* Return the `struct tm' representation of *TIMER in UTC,
   using *TP to store the result.  */
extern struct tm *gmtime_r (__const time_t *__restrict __timer,
                            struct tm *__restrict __tp) __THROW;

代码实现如下:

#include <iostream>
#include <time.h>
using namespace std;
int main()
{
    struct tm mytm;
    time_t  t=time(NULL);
    cout<<"t is:"<<t<<endl;
    gmtime_r(&t,&mytm);
    cout<<"tm_year is:"<<mytm.tm_year<<endl;
    cout<<"tm_mon  is:"<<mytm.tm_mon<<endl;

    struct tm *p;
    p=gmtime(&t);
    cout<<"tm_year is:"<<p->tm_year<<endl;
    cout<<"tm_mon  is:"<<p->tm_mon<<endl;
}

编译执行如下:

$
$gcc -lstdc++ l_gmtime.cpp 
$./a.out 
t is:1532959967
tm_year is:118
tm_mon  is:6
tm_year is:118
tm_mon  is:6
$

1.、通过time() 获取时间戳

2、第一种方法:通过gmtime_r(&t,&mytm); 把 时间戳t 转换成 分解时间 存入 mytm

      第二种方法:先定义一个指向struct tm 的指针p,然后p=gmtime(&t)  通过返回值实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值