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

localtime() 与gmtime()函数都可以将时间戳time_t类型的时间换算成分解时间struct tm 。区别在于

 gmtime()是转换成标准时间,即UTC时间

localtime() 会考虑时区的因素。稍后代码实现演示。

####

【localtime()】

函数原型在time.h中,localtime_r()版本 增加了一个 struct tm* 类型的参数,用于保存结果

/* Return the `struct tm' representation
   of *TIMER in the local timezone.  */
extern struct tm *localtime (__const time_t *__timer) __THROW;
__END_NAMESPACE_STD

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

代码实现

通过time()函数获取时间戳,然后分别通过localtime()和gmtime()函数转换,打印时区 tm_zone信息

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    time_t myt=time(NULL);
    time_t gmt=time(NULL);
    struct tm *mytm;
    struct tm *gmtm;

    cout<<"myt is:"<<myt<<endl;
    cout<<"gmt is:"<<gmt<<endl;

    mytm=localtime(&myt);
    //gmtm=gmtime(&gmt);
    cout<<"mytm.tm_year is:" <<mytm->tm_year<<endl;
    cout<<"mytm.tm_mon is:" <<mytm->tm_mon<<endl;
    cout<<"mytm.tm_zone is:"<<mytm->tm_zone<<endl;

    gmtm=gmtime(&gmt);
    cout<<"gmtm.tm_year is:"<<gmtm->tm_year<<endl;
    cout<<"gmtm.tm_mon is:"<<gmtm->tm_mon<<endl;
    cout<<"gmtm.tm_zone is:"<<gmtm->tm_zone<<endl;

编译执行如下:

$
$gcc -lstdc++ l_localtime.cpp 
$./a.out 
myt is:1533018523
gmt is:1533018523
mytm.tm_year is:118
mytm.tm_mon is:6
mytm.tm_zone is:CST
gmtm.tm_year is:118
gmtm.tm_mon is:6
gmtm.tm_zone is:GMT
$

显示结果中 tm_zone 字段 一个是CST,一个是GMT,具体时区的缩写可以网上搜索下。

上面有段注释的代码 //gmtm=gmtime(&gmt); 该行的位置会影响结果的显示,具体的原因目前还不清楚,应该指向STL静态区的指针有关。在网上 找了另一种实现方式:

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    time_t myt=time(NULL);
    time_t gmt=time(NULL);
    //struct tm *mytm;
    //struct tm *gmtm;
    struct tm mytm;
    struct tm gmtm;

    cout<<"myt is:"<<myt<<endl;
    cout<<"gmt is:"<<gmt<<endl;

    mytm=*localtime(&myt);
    gmtm=*gmtime(&gmt);

    cout<<"mytm.tm_zone is:"<<mytm.tm_zone<<endl;
    cout<<"gmtm.tm_zone is:"<<gmtm.tm_zone<<endl;
}

猜你喜欢

转载自blog.csdn.net/natpan/article/details/81302671