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 教學

正確的系統時間是日誌分析、定時任務、資料庫同步、SSL 憑證驗證的基石。本文整理 時區設定三大法、時間修改指令、硬體時鐘同步、NTP 自動校時 完整操作手冊。

一、時區設定 (三大通用法)

方法 1:互動式選擇 (tzselect) — 通用

tzselect
# 依提示選擇洲 → 國家 → 時區
# 最後輸出建議設定指令,需手動執行

方法 2:圖形/文字選單工具 — 發行版專用

# RHEL/CentOS/Fedora
timedatectl set-timezone Asia/Taipei
# 或舊版
system-config-date  # 圖形
timeconfig          # 文字 (極舊版)

# Debian/Ubuntu
dpkg-reconfigure tzdata  # 互動式選單
# 或
timedatectl set-timezone Asia/Taipei

方法 3:直接複製/連結區域檔 — 最直接、通用

# 複製法
cp /usr/share/zoneinfo/Asia/Taipei /etc/localtime

# 連結法 (推薦,隨 tzdata 套件更新自動同步)
ln -sf /usr/share/zoneinfo/Asia/Taipei /etc/localtime

# 驗證
date -R
# 輸出含 +0800 即正確

二、系統時間查看與手動修改

查看

date                    # 完整日期時間
date +"%Y-%m-%d %H:%M:%S"  # 自定義格式
date -R                 # RFC 2822 格式 (含時區)
hwclock -r              # 硬體時鐘 (BIOS 時間)

手動修改系統時間

# 日期
date -s "2024-12-25"
# 時間
date -s "14:30:00"
# 日期時間一次設定
date -s "2024-12-25 14:30:00"

三、寫入硬體時鐘 (BIOS) — 重開機不失效

# 系統時間 → 硬體時鐘 (UTC 模式)
hwclock -w --utc
# 或本地時間模式 (Windows 雙系統常用)
hwclock -w --localtime

# 反向同步:硬體 → 系統 (開機自動執行)
hwclock -s --utc

關鍵選擇:純 Linux 環境用 --utc (硬體儲存 UTC);Windows 雙系統用 --localtime (硬體儲存本地時間),雙邊協調一致即可。

四、NTP 自動網路校時 (生產環境標準)

Chrony (現代標準,RHEL 7+/CentOS 7+/Fedora/Ubuntu 20.04+)

# 安裝
dnf install chrony      # RHEL/CentOS/Fedora
apt install chrony      # Debian/Ubuntu

# 配置 /etc/chrony.conf
pool 3.tw.pool.ntp.org iburst
pool 3.asia.pool.ntp.org iburst

# 啟用
systemctl enable --now chronyd

# 即時同步
chronyc makestep

# 狀態查看
chronyc sources -v
chronyc tracking

NTPD (傳統,舊版系統)

yum install ntp
systemctl enable --now ntpd
ntpdate -u pool.ntp.org  # 立即同步
# 定時任務 (不推薦,chrony 內建)
# * * * * * /usr/sbin/ntpdate pool.ntp.org > /dev/null 2>&1

systemd-timesyncd (極簡,systemd 整合)

# /etc/systemd/timesyncd.conf
[Time]
NTP=3.tw.pool.ntp.org
FallbackNTP=time.google.com
systemctl enable --now systemd-timesyncd
timedatectl status

五、timedatectl 統一管理介面 (systemd 系統)

timedatectl                    # 總覽
timedatectl list-timezones     # 所有时区
timedatectl set-timezone Asia/Taipei
timedatectl set-time "2024-12-25 14:30:00"
timedatectl set-ntp true       # 啟用網路校時 (chrony/timesyncd)
timedatectl status

六、虛擬機/容器特殊處理

  • VMware/VirtualBox:安裝 Guest Additions/Tools 啟用時間同步,或關閉宿主機同步改用內部 NTP
  • Docker 容器:掛載宿主機 /etc/localtime:/etc/localtime:ro、/etc/timezone:/etc/timezone:ro,或環境變數 TZ=Asia/Taipei

結語

現代 Linux 時間管理三步走:1. ln -sf /usr/share/zoneinfo/Asia/Taipei /etc/localtime 固定時區、2. timedatectl set-ntp true 啟用 chrony 自動校時、3. hwclock -w --utc 同步硬體時鐘。棄用手動 date -s 与 crontab ntpdate,擁抱 chrony 與 timedatectl 統一介面。

Copyright © Windows教程網 All Rights Reserved