1. 系统时间和硬件时间

在Linux中有硬件时钟与系统时钟两种时钟。

硬件时钟是指主机板上的时钟设备,也就是通常可在BIOS画面设定的时钟。

系统时钟则是指kernel中的时钟。所有Linux相关指令与函数都是读取系统时钟的设定。

因为存在两种不同的时钟,那么它们之间就会存在差异。

当Linux启动时,系统时钟会去读取硬件时钟的设定,之后系统时钟即独立运作。

用date命令对系统时间进行设置后,并不会去修改硬件时钟,所以系统重启后,系统时间还算会去读取硬件时间,这就是为何date设置失效到原因。

因此,需要在设置系统时间后,将系统时间同步到硬件时钟。

2. 系统时间相关命令

2.1. 查看系统时间:date

[root@m01 ~]# date
Thu Oct 31 11:03:51 CST 2024

2.2. 查看系统时区:date -R

[root@m01 ~]# date -R
Thu, 31 Oct 2024 11:03:54 +0800

2.3. 修改系统时间:(不会调整时区)

date -s "2021-04-29 15:51:50" 

2.4. 修改时区:

修改时区的几种方式:

● ‌使用timedatectl命令‌:
  ○ 查看当前时区:timedatectl
  ○ 设置新时区:sudo timedatectl set-timezone Asia/Shanghai‌
● ‌手动修改/etc/localtime文件‌:
  ○ 备份原有时区文件:sudo cp /etc/localtime /etc/localtime.bak
  ○ 创建新的符号链接:sudo ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime‌
● ‌使用tzselect命令‌:
  ○ 运行tzselect命令,根据提示选择地区、城市等信息,最后选择想要的时区

3. 硬件时间相关命令

clock/hwclock两个命令相同

#读取并打印硬件时钟(read hardware clock and print result)
hwclock -r 或 hwclock --show    
#将硬件时钟同步到系统时(set the system time from the hardware clock)
hwclock -s, hwclock --hctosys
#将系统时钟同步到硬件时钟(set the hardware clock to the current system time)    
hwclock -w, hwclock --systohc  

4. 时间同步

会从时间源同步系统时间,并同时修改硬件时间

yum install chrony -y  

# 配置 chrony 使用国内服务器
sed -i 's/^pool.*pool.ntp.org/#&/' /etc/chrony.conf
cat >> /etc/chrony.conf <<EOF
server ntp.aliyun.com iburst
server ntp.tencent.com iburst
server ntp.ntsc.ac.cn iburst
server time1.cloud.tencent.com iburst
EOF

systemctl restart chronyd
chronyc sources -v 
chronyc makestep 
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐