Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 系統時間修改與硬件時鐘同步完整教程

編輯:Linux 教學

Linux 擁有雙時鐘體系:系統時鐘(核心維護)與硬件時鐘/RTC(主板 CMOS)。本文詳解查看、修改、同步、NTP 網路對時、時區設置、虛擬機特殊處理。

雙時鐘架構

核心所有時間 API(time()、gettimeofday()、clock_gettime()、文件時間戳)均使用系統時鐘。

查看時間


date                      # 系統時間
date -R                   # RFC 2822 格式(含時區)
timedatectl               # systemd 統一視圖
hwclock --show            # 硬件時鐘
hwclock -r                # 同義

修改系統時間


# 格式:MMDDhhmm[[CC]YY][.ss]
date 042612492005         # 04月26日 12:49 2005年

# 字符串格式(推薦)
date -s "2024-12-25 14:30:00"
date --set="2024-12-25 14:30:00"

# 僅修改日期/時間
date -s "2024-12-25"
date -s "14:30:00"

修改硬件時鐘


hwclock --set --date="2024-12-25 14:30:00"
# 或
clock --set --date="2024-12-25 14:30:00"  # 兼容 Alpha 架構

雙向同步


# 系統時鐘 → 硬件時鐘(寫入 CMOS)
hwclock -w
hwclock --systohc

# 硬件時鐘 → 系統時鐘(啟動時自動執行)
hwclock --hctosys

時區設置


# 方法 1:複製區域文件(通用)
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# 方法 2:timedatectl(systemd)
timedatectl set-timezone Asia/Shanghai

# 方法 3:tzdata 交互式
dpkg-reconfigure tzdata   # Debian/Ubuntu
tzselect                  # 手動選擇生成 TZ 變量

驗證:date -R 輸出應含 +0800 或 CST。

RTC 模式:UTC vs 本地時間


# 查看當前模式
timedatectl | grep "RTC in local TZ"
# 或
cat /etc/adjtime   # 最後一行 UTC/LOCAL

# 設置 RTC 使用 UTC(推薦,避免夏令時/雙系統衝突)
timedatectl set-local-rtc 0
# 或手動編輯 /etc/adjtime 最後一行改為 UTC

# 雙啟動 Windows 需本地時間
timedatectl set-local-rtc 1 --adjust-system-clock

NTP 網路時間同步

安裝


yum -y install chrony       # RHEL 7+/CentOS 7+ 推薦
# 或
yum -y install ntp          # 傳統 ntpd
apt-get install chrony      # Debian/Ubuntu

配置 chrony(/etc/chrony.conf)


pool ntp.aliyun.com iburst
pool cn.pool.ntp.org iburst
pool time.google.com iburst

# 允許局域網客戶端同步
allow 192.168.0.0/16

systemctl enable --now chronyd
chronyc sources -v        # 查看源狀態
chronyc tracking          # 同步精度

虛擬機/容器特殊處理

  • KVM/QEMU:啟用 kvm-clock 時鐘源,宿主機運行 NTP,客戶機安裝 qemu-guest-agent 同步
  • VMware:安裝 VMware Tools,啟用時間同步
  • Docker 容器:共享宿主機核心,時間同步;--privileged 可在容器內修改影響宿主機
  • OpenVZ/LXC:無法修改系統時間,僅可改時區,需宿主機同步

圖形化工具


# GNOME
gnome-control-center datetime

# KDE
systemsettings5 kcm_clock

# 通用 systemd
timedatectl
Copyright © Windows教程網 All Rights Reserved
時鐘來源特點
系統時鐘核心內存變量精度高(納秒)、啟動時從 RTC 讀取、運行時獨立
硬件時鐘 (RTC)主板 CMOS(電池供電)斷電保持、精度較低、BIOS 可設置