就在刚才,一位网友的Linux服务器上获取时间总是和本地电脑windows系统时间相差8小时,一直不知道是为什么?后来联系上了我,我去看了一下他写的PHP代码,得到结果:
1、代码是没有任何问题的?
2、php.ini 配置文件中也启用了 date.timezone = PRC;
后来我用xshell连接上了他的服务器,我执行date命令,先检查当前服务器的时间:
[root@localhost ~]# date
Wed Mar 10 12:56:28 CST 2021
结果发现,是他的Linux服务器本身的时间不准,他的服务器是centos7。
原因:
原因其实不用多说,大家都知道了,硬件时钟不与UTC时间一致问题,时区不一样所引起的。
CST应该是指(China Shanghai Time,东八区时间)
UTC应该是指(Coordinated Universal Time,标准时间)
所以,这2个时间实际上应该相差8个小时。
解决方法
知道了原因,解决问题就容易多了,由于服务器时间相差8小时这个问题详细讲的话,解决方法其实有很多种,我就给大家分享两种我最常用的解决方法吧!具体如下:
第一步:用ntpdate命令来让时间同步
1、安装ntpdate
# CentOS:
[root@localhost ~]# yum install ntpdate -y
# Debian/Ubuntu:
[root@localhost ~]# apt install ntpdate -y
2、执行ntpdate时间同步命令
# CentOS/Debian/Ubuntu 执行:
[root@localhost ~]# ntpdate 0.asia.pool.ntp.org
如果上面时间同步失败,连接不上服务器,可以用以下命令:
[root@localhost ~]# ntpdate ntp1.aliyun.com
ntpdate time.nist.gov
3、现在再去查看时间信息,可以用“date”或“timedatectl”命令。
第二步:改硬件时间
同步成功后调整硬件时间,我直接用命令“hwclock -w”来同步硬件时间。
以下是hwclock其它相关命令:
hwclock --show 查看硬件的时间 hwclock --set --date '2023-03-02 18:22:00' 设置硬件时间 hwclock --hctosys 设置系统时间和硬件时间同步 hwclock -s 让系统时间和硬件时间保持一致
第三步:改系统时间
再去改系统时间。如果第二个步骤搞定的话,这里也可以不设置。例如:
date -s ‘10:10:00’
第四步:重设系统时区
第一种方法:当地时间替换为上海
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo 'Asia/Shanghai' >/etc/timezone
#jenkins时需要使用root用户权限
docker exec -u root -it jenkins /bin/bash
或者
第一步:删除/etc/localtime,命令:
rm -rf /etc/localtime
第二步:复制上海时区,命令:
cp /usr/share/zoneinfo/Asia/Shanghai /etc/locatime
注意:需要重启服务器才会生效,推荐大家用第二种方法。
第二种方法:环境变量/etc/profile
1、在 /etc/profile 文件中增加一行:
export TZ='CST-8'
2、使文件立即生效,执行命令:
[root@localhost ~]# source /etc/profile
或者
[root@localhost ~]# ./etc/profile
总结:
Linux系统与windows系统时间不一致相差8小时这就算是完美的解决了。
最后再来说一下解决服务器时间与实际时间相差8小时的整个思路,具体如下:
原因:由于时区不同,校准时间后导致服务器时间与实际时间之前相差8小时,给出如下解决方案
第一步:在 /etc/profile 文件中增加一行 export TZ='CST-8'
第二步:使文件立即生效:source /etc/profile 或者 . /etc/profile
第三步:同步网络时间:ntpdate time.nist.gov
第四步:同步成功后调整硬件时间:hwclock -w
第五步:最后,可以date一下,看时间是否准确?