目录
linux时钟概述
- linux系统有两个时钟:一个是硬件时钟,即BIOS时间;另一个是系统时钟,是linux系统Kernel(内核)时间。
- 在linux系统上程序运行时读取的时间都是系统Kernel(内核)时间。
- 每次Linux启动时,系统Kernel(内核)会先去读取硬件时钟的设置(但是此时的硬件时间不一定是准确的),然后系统时钟就会独立于硬件继续运作。
- 综上所述,所以想要永久修改linux时间并使得时间准确,就需要永久修改硬件时间,不然每次重新启动linux时,系统时间又变回之前的硬件时间。
linux时钟相关命令
- 系统Kernel(内核)时钟的相关命令是timedatectl 或者 date;
- 硬件BIOS时钟相关命令是hwclock 或者 clock。
如何查看时区、时间
- 查看时区
[root@localhost ~]# date -R; cat /etc/sysconfig/clock
Thu, 28 Sep 2017 00:31:54 +0800
ZONE="Asia/Shanghai"
##我们国家的东八区(+0800)
- 查看系统时间
[root@localhost ~]# date
Thu Aug 30 10:05:59 CST 2018
- 查看硬件时间
[root@localhost ~]# hwclock --show
或者
[root@localhost ~]# clock --show
Thu 30 Aug 2018 11:06:34 AM CST -0.360419 seconds
综上可以看出:系统时间和硬件时间并不一致,其实系统时间才是准确的。
如何更新修改时间
现在我们假设系统时间和硬件时间都不准确,需要更新系统时间和硬件时间并使得两个时间准确一致。
- 假设系统的版本是Centos7系列
#更新系统时间---年月日
[root@Centos7.x ~]# timedatectl set-time 2018-08-30
#更新系统时间---时分秒
[root@Centos7.x ~]# timedatectl set-time 10:25:17
###以上两步都是人为设置时间,并不准确,所以有网络的情况下我们一般用ntpdate命令更新系统时间
[root@Centos7.x ~]# ntpdate ntp1.aliyun.com
#更新时区(亚洲-中国-上海)
[root@Centos7.x ~]# timedatectl set-timezone Asia/Shanghai
#设置硬件时间
[root@Centos7.x ~]# hwclock --set --date="06/18/14 14:55" (月/日/年时:分:秒)
或者
[root@Centos7.x ~]# clock --set --date="06/18/14 14:55" (月/日/年时:分:秒)
#将硬件时钟调整为与系统时钟一致
[root@Centos7.x ~]# timedatectl set-local-rtc 1
或者
[root@Centos7.x ~]# hwclock --systohc --localtime (好像这个更有效)
#最后将日期写入CMOS永久生效
[root@Centos7.x ~]# clock -w
或者
[root@Centos7.x ~]# hwclock -w
#再次查看系统时间和硬件时间,他们就一致了
- 假设系统的版本是Centos6系列
#更新系统时间---年月日
[root@Centos6.x ~]#date -s 2018-08-30
#更新系统时间---时分秒
[root@Centos6.x ~]# date -s 10:25:17
###以上两步都是人为设置时间,并不准确,所以有网络的情况下我们一般用ntpdate命令更新系统时间
[root@Centos6.x ~]# ntpdate ntp1.aliyun.com
#更新时区(亚洲-中国-上海)
[root@Centos6.x ~]# vi /etc/sysconfig/clock
ZONE="Asia/Shanghai"
#设置硬件时间
[root@Centos6.x ~]# hwclock --set --date="06/18/14 14:55" (月/日/年时:分:秒)
或者
[root@Centos6.x ~]# clock --set --date="06/18/14 14:55" (月/日/年时:分:秒)
#硬件时钟与系统时钟同步:hc代表硬件时间,sys代表系统时间,即用硬件时钟同步系统时钟
[root@Centos6.x ~]# hwclock --hctosys
或者
[root@Centos6.x ~]# clock --hctosys
#系统时钟和硬件时钟同步:即用系统时钟同步硬件时钟
[root@Centos6.x ~]# hwclock --systohc
或者
[root@Centos6.x ~]# clock --systohc
#最后将日期写入CMOS永久生效
[root@Centos6.x ~]# clock -w
或者
[root@Centos6.x ~]# hwclock -w
#再次查看系统时间和硬件时间,他们就一致了