为Linux配置时区和同步互联网时间

最优方案——使用timedatectl命令

timedatectl 是现代 Linux 发行版中用于管理时间和时区的工具

查看和修改时区配置

1
2
3
4
5
6
# 查看当前时区
timedatectl
# 列出所有可用的时区
timedatectl list-timezones
# 设置新的时区, 这里以 Asia/Shanghai 为例
timedatectl set-timezone Asia/Shanghai

开启和关闭网络同步

1
2
3
4
# 使系统时间自动与网络同步
timedatectl set-ntp on
# 关闭网络时间同步
timedatectl set-ntp off

PlanB——手动配置

对于类似于 alpine 这种轻量级发行版或者特别古老的 Linux, 需要手动配置

手动修改时区

1
2
3
4
5
6
# 时区文件通常位于 /usr/share/zoneinfo
ls /usr/share/zoneinfo
# 将目标时区文件复制到 /etc/localtime
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# 更新 TZ 配置文件
echo "Asia/Shanghai" | sudo tee /etc/timezone

使用chrony服务同步时间

1
2
3
4
5
6
# 安装 chrony
apt / yum install chrony -y
# 启动服务
systemctl enable chronyd && systemctl start chronyd
# 检查时间同步状态
chronyc tracking