| 工具 | 所屬項目 | 狀態 | 適用系統 |
| tzconfig | Debian 專有 | 已棄用/移除 | Debian 9 之前、Ubuntu 16.04 之前 |
| tzselect | glibc 附帶 | 維護模式 | 所有 glibc 系統 (不修改系統配置) |
| timedatectl | systemd | 現代標準 | systemd 系統 (RHEL 7+, Ubuntu 16.04+, Debian 9+, Arch...) |
timedatectl:現代標準用法 (推薦)
# 查看當前狀態
timedatectl status
# 列出所有时区
timedatectl list-timezones
# 過濾中國時區
timedatectl list-timezones | grep -i asia
# 設置時區 (立即生效,持久化)
timedatectl set-timezone Asia/Shanghai
# 或 Asia/Chongqing (同一時區不同別名)
# 設置時間 (需 root)
timedatectl set-time "2024-01-15 14:30:00"
# 啟用 NTP 同步
timedatectl set-ntp true
# 查看 NTP 同步狀態
timedatectl show-timesync --all
tzselect:無 systemd 系統的交互式選擇
tzselect
# 交互式選擇:大洲 -> 國家 -> 城市
# 最終輸出建議:
# TZ='Asia/Shanghai'; export TZ
# 並提示需手動執行:
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
缺點:不自動修改系統配置,需手動複製 zoneinfo 文件,不持久化環境變量。
tzconfig:歷史遺留 (僅供參考)
# Debian/Ubuntu 舊版
sudo tzconfig
# 交互式選擇後自動更新 /etc/localtime
底層機制:/etc/localtime 與 /usr/share/zoneinfo
/usr/share/zoneinfo/:IANA 時區數據庫編譯後的二進制文件樹
/etc/localtime:副本或符號鏈接,指向當前時區文件
/etc/timezone:(Debian/Ubuntu) 純文本記錄時區名稱,供工具讀取
最佳實踐:使用符號鏈接,IANA 數據庫更新 (tzdata 包升級) 後自動生效:
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
容器化環境特殊處理
# Dockerfile 中設置 (構建時)
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 運行時覆蓋 (docker run)
docker run -e TZ=Asia/Shanghai ...
# Kubernetes Pod
env:
- name: TZ
value: "Asia/Shanghai"
# 或掛載主機時區
volumeMounts:
- name: tz
mountPath: /etc/localtime
subPath: localtime
volumes:
- name: tz
hostPath:
path: /etc/localtime
自動化腳本:批量服務器時區統一
#!/bin/bash
# set-timezone.sh
TARGET_TZ="Asia/Shanghai"
NTP_SERVER="ntp.aliyun.com"
# 1. 設置時區
timedatectl set-timezone "$TARGET_TZ" 2>/dev/null || \
ln -sf "/usr/share/zoneinfo/$TARGET_TZ" /etc/localtime
# 2. 啟用 NTP
timedatectl set-ntp true 2>/dev/null || \
systemctl enable --now systemd-timesyncd 2>/dev/null || \
systemctl enable --now ntpd 2>/dev/null || \
systemctl enable --now chronyd 2>/dev/null
# 3. 配置 NTP 服務器 (chrony 示例)
if command -v chronyc &>/dev/null; then
sed -i "s/^pool .*/pool $NTP_SERVER iburst/" /etc/chrony.conf
systemctl restart chronyd
fi
# 4. 驗證
timedatectl status
echo "Timezone unified to $TARGET_TZ"
常見坑點與排查
| 現象 | 原因 | 解決 |
| 修改後重啟失效 | 複製而非鏈接 zoneinfo,tzdata 升級後未同步 | 改用 ln -sf 符號鏈接 |
| 應用程序時間錯誤 | JVM/Go/Python 進程啟動後緩存舊時區 | 重啟應用或設置 TZ 環境變量 |
| 雙系統時間差 8 小時 | Windows 用本地時間,Linux 用 UTC | Windows 改用 UTC 或 Linux timedatectl set-local-rtc 1 |
| cron 定時任務錯亂 | cron 守護進程需重啟感知新時區 | systemctl restart cron |
總結:systemd 系統請直接用 timedatectl set-timezone Asia/Shanghai,一條命令搞定查看、設置、持久化、NTP 聯動。非 systemd 系統用 ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime。容器環境通過 TZ 環境變量或掛載 /etc/localtime。統一時區、啟用 NTP、符號鏈接——三大鐵律守住時間準確性。