localtime时间使用

在linux环境,应用需要记录KPI的数据统计,代码中获取时间函数,localtime(),asctime查看,获取事件为东八区的时间,与当前系统时间一致,而从另一台服务器远程ssh 启动此应用,获取的时间为UTC 的时间,并未换算为东八区时间;

# ssh  10.118.203.140 "/time"
root@10.118.203.140's password:
asctime(now) is  Mon Dec 18 00:43:25 2017
# ./time
asctime(now) is  Mon Dec 18 13:43:34 2017


代码示例:

#include 
#include <string>
#include <time.h>
#include <string.h>
#include 

using namespace std;
using std::string;

int main()
{
    time_t t=time(NULL);
    struct tm *now;
    now = localtime(&t);
    cout << "asctime(now) is  " << asctime(now) << endl;
    return 0;
}


通过man 查看localtime()的时间获取,与环境变量timezone相关;

# ssh  10.118.203.140 "env;/home/lax/time"
[email protected]'s password: 
SELINUX_ROLE_REQUESTED=
SHELL=/bin/bash
SSH_CLIENT=10.118.203.140 39588 22
SELINUX_USE_CURRENT_RANGE=
QTDIR=/usr/lib64/qt-3.3
QTINC=/usr/lib64/qt-3.3/include
USER=root
MAIL=/var/mail/root
PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
PWD=/root
KDE_IS_PRELINKED=1
LANG=en_US.UTF-8
MODULEPATH=/usr/share/Modules/modulefiles:/etc/modulefiles
LOADEDMODULES=
KDEDIRS=/usr
SELINUX_LEVEL_REQUESTED=
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SHLVL=1
HOME=/root
LOGNAME=root
QTLIB=/usr/lib64/qt-3.3/lib
CVS_RSH=ssh
SSH_CONNECTION=10.118.203.140 39588 10.118.203.140 22
MODULESHOME=/usr/share/Modules
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
module=() {  eval `/usr/bin/modulecmd bash $*`
}
_=/bin/env

asctime(now) is  Mon Dec 18 00:53:29 2017

ssh 查看env里确实没有TZ的时区设置;

# ssh  10.118.203.140 "TZ='Asia/Shanghai';export TZ;env;/home/lax/time"
[email protected]'s password: 
SELINUX_ROLE_REQUESTED=
SHELL=/bin/bash
SSH_CLIENT=10.118.203.140 39681 22
SELINUX_USE_CURRENT_RANGE=
QTDIR=/usr/lib64/qt-3.3
QTINC=/usr/lib64/qt-3.3/include
USER=root
MAIL=/var/mail/root
PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
PWD=/root
KDE_IS_PRELINKED=1
LANG=en_US.UTF-8
MODULEPATH=/usr/share/Modules/modulefiles:/etc/modulefiles
TZ=Asia/Shanghai
LOADEDMODULES=
KDEDIRS=/usr
SELINUX_LEVEL_REQUESTED=
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SHLVL=1
HOME=/root
LOGNAME=root
QTLIB=/usr/lib64/qt-3.3/lib
CVS_RSH=ssh
SSH_CONNECTION=10.118.203.140 39681 10.118.203.140 22
MODULESHOME=/usr/share/Modules
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
module=() {  eval `/usr/bin/modulecmd bash $*`
}
_=/bin/env

asctime(now) is  Mon Dec 18 14:09:58 2017

在ssh的session里,先预先设置TZ的环境变量,再运行应用,获取的时间与服务器上时间一致。

你可能感兴趣的:([c++学习])