talk is cheap, show me the code.
Linux的时间分为System Clock(系统时间)和 Real Time Clock (硬件时间,简称RTC)。
-
系统时间
指当前Linux Kernel中的时间
-
硬件时间
主板上有电池供电的时间
查看系统时间 date
[tanpeng@itplh ~]$ date
Fri Mar 27 17:53:52 CST 2020
设置系统时间的命令 date -s "月/日/年 时:分:秒"
[tanpeng@itplh ~]$ sudo date -s "02/27/2020 19:00:00"
Thu Feb 27 19:00:00 CST 2020
[tanpeng@itplh ~]$ date
Thu Feb 27 19:00:08 CST 2020
查看硬件时间的命令 hwclock
[tanpeng@itplh ~]$ sudo hwclock
Fri 27 Mar 2020 05:56:39 PM CST -0.453631 seconds
设置硬件时间的命令 hwclock –set –date = (月/日/年 时:分:秒)
[tanpeng@itplh ~]$ sudo hsclock -s "02/27/2020 19:00:00"
Thu Feb 27 19:00:00 CST 2020
[tanpeng@itplh ~]$ date
Thu Feb 27 19:00:08 CST 2020
上述提到的是手动设置时间到一个时间点,可能与当前网络的时间有误差
与时间服务器上的时间同步的方法
-
安装
ntpdate
工具yum -y install ntp ntpdate
-
设置系统时间与网络时间同步
ntpdate cn.pool.ntp.org
-
将系统时间写入硬件时间
hwclock --systohc
example
[tanpeng@cloud02 ~]$ sudo ntpdate cn.pool.ntp.org
27 Mar 18:20:22 ntpdate[17937]: step time server 111.230.189.174 offset 2502162.541489 sec
[tanpeng@cloud02 ~]$ sudo hwclock --systohc
[tanpeng@cloud02 ~]$ date
Fri Mar 27 18:20:47 CST 2020
[tanpeng@cloud02 ~]$ sudo hwclock
Fri 27 Mar 2020 06:20:56 PM CST -0.609821 seconds