linux系统时间有两个,一个是硬件时间,即BIOS时间,就是我们进行CMOS设置时看到的时间,另一个是系统时间,是linux系统Kernel时间。当Linux启动时,系统Kernel会去读取硬件时钟的设置,然后系统时钟就会独立于硬件运作。有时我们会发现系统时钟和硬件时钟不一致,因此需要执行时间同步。

date -R 查看当前时区

一、date 查看/设置系统时间

1、将日期设置为2020年02月15日

[root@linux-node ~]# date -s 15/02/20

2、将时间设置为14点20分50秒

[root@linux-node ~]# date -s 14:20:50

3、将时间设置为2020年02月15日14点16分30秒(MMDDhhmmYYYY.ss)

[root@linux-node ~]# date 1502141620.30

[root@linux-node ~]# date -s "2020-02-15 14:16:30"

二、hwclock/clock 查看/设置硬件时间

1、查看系统硬件时钟

[root@linux-node ~]# hwclock  --show 或者

[root@linux-node ~]# clock  --show

2、设置硬件时间

[root@linux-node ~]# hwclock --set --date="15/02/20 14:55"

(月/日/年时:分:秒) 或者

[root@linux-node ~]# clock --set --date="15/02/20 14:55"

(月/日/年时:分:秒)

[root@linux-node ~]# hwclock -w 保存修改结果

三、同步系统及硬件时钟

[root@linux-node ~]# hwclock --hctosys 或者

[root@linux-node ~]# clock --hctosys

备注:hc代表硬件时间,sys代表系统时间,以硬件时间为基准,系统时间找硬件时间同步

[root@linux-node ~]# hwclock --systohc或者

[root@linux-node ~]# clock --systohc

备注:以系统时间为基准,硬件时间找系统时间同步

方法二

时区设置用tzselect

命令来实现。但是通过tzselect命令设置TZ这个环境变量来选择的时区,需要将变量添加到.profile文件中。

一、tzselect命令执行

执行tzselect命令 --> 选择Asia --> 选择China --> 选择east China

- Beijing, Guangdong, Shanghai, etc-->然后输入1。

执行完tzselect命令选择时区后,时区并没有更改,只是在命令最后提示你可以执行 TZ=’Asia/Shanghai’;

export TZ 并将这行命令添加到.profile中,然后退出并重新登录。

二、修改配置文件来修改时区

[root@linux-node ~]# echo "ZONE=Asia/Shanghai" >>

/etc/sysconfig/clock

[root@linux-node ~]# rm -f /etc/localtime

#链接到上海时区文件

[root@linux-node ~]# ln -sf /usr/share/zoneinfo/Asia/Shanghai

/etc/localtime

执行完上述过程后,重启机器,即可看到时区已经更改。

备注:

在centos7中设置时区的命令可以通过 timedatectl 命令来实现

[root@linux-node ~]# timedatectl set-timezone

Asia/Shanghai

ntp客户端配置

1.检查系统是否安装了NTP包(linux系统一般自带NTP4.2),没有安装我们直接使用yum命令在线安装: yum

install ntp (yum install ntp ntpdate -y)

[root@linux-node ~]# rpm -qa | grep ntp

2.启动NTP时间服务器:

[root@linux-node ~]# systemctl status ntpd

[root@linux-node ~]# systemctl start ntpd (service ntpd start

)

[root@linux-node ~]# systemctl enable ntpd

3.设置NTP开机自动启动:chkconfig ntpd on

4.查看NTP是否正常运行:netstat -t l unp | grep ntp

修改/etc/ntp.conf文件,内容如下

#注释掉其他上游时间服务器

#配置上游时间服务器为本地的ntpd Server服务器

server 192.168.0.163

#配置允许上游时间服务器主动修改本机的时间

restrict 192.168.0.163 nomodify notrap noquery

5。与ntpd Server同步一下

[root@linux-node ~]# ntpdate -u 192.168.0.163

查看状态

[root@linux-node ~]# ntpq -p

ntp服务,默认只会同步系统时间。如果想要让ntp同时同步硬件时间,可以设置/etc/sysconfig/ntpd文件,在/etc/sysconfig/ntpd文件中,添加

SYNC_HWCLOCK=yes 这样,就可以让硬件时间与系统时间一起同步。