如何在Debian 9上设置或者更改时区

时间:2020-03-05 15:27:31  来源:igfitidea点击:

对于许多与系统相关的任务和过程,使用正确的时区非常重要。
例如,cron守护程序使用系统的时区执行cron作业,而日志文件中的时间戳基于同一系统的时区。

系统的时区是在安装过程中设置的,但以后可以轻松更改。
本教程介绍了如何在Debian 9上设置或者更改时区。

准备工作

我们登录的用户必须具有sudo特权才能更改系统的时区。

检查当前时区

在Debian和其他现代Linux发行版中,可以使用“ timedatectl”命令显示和设置当前系统的时间和时区。

timedatectl

如下图所示,系统的时区设置为“美国/芝加哥”:

Local time: Mon 2019-03-11 16:46:45 CDT
  Universal time: Mon 2019-03-11 21:46:45 UTC
        RTC time: Mon 2019-03-11 21:46:45
       Time zone: America/Chicago (CDT, -0500)
 Network time on: yes
NTP synchronized: no
 RTC in local TZ: no

通过将“/etc/localtime”符号链接到“/usr/share/zoneinfo”目录中的二进制时区标识符来配置系统时区。
检查时区的另一个选项是使用ls命令显示symlink指向的路径:

ls -l /etc/localtime
lrwxrwxrwx 1 root root 37 Jan 23 03:19 /etc/localtime -> ../usr/share/zoneinfo/America/Chicago

在Debian中更改时区

在更改时区之前,我们需要找出要使用的时区的长名称。
时区命名约定通常使用“地区/城市”格式。

要列出所有可用时区,可以在“/usr/share/zoneinfo”目录中列出文件,也可以使用“ timedatectl”命令。

timedatectl list-timezones
...
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
...

一旦确定了哪个时区适合位置,请以sudo用户身份运行以下命令:

sudo timedatectl set-timezone your_time_zone

例如,要将系统的时区更改为“欧洲/卢布尔雅那”,我们可以运行:

sudo timedatectl set-timezone Europe/Ljubljana

通过发出“ timedatectl”命令来验证更改:

timedatectl
Local time: Mon 2019-03-11 22:51:27 CET
  Universal time: Mon 2019-03-11 21:51:27 UTC
        RTC time: Mon 2019-03-11 21:51:26
       Time zone: Europe/Ljubljana (CET, +0100)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

通过创建符号链接来更改时区

如果我们运行的是Debian的旧版本,并且系统上没有'timedatectl'命令,则可以通过将'/etc/localtime'符号链接到'/usr/share/zoneinfo'目录中的时区来更改时区。

删除当前的“/etc/localtime”文件或者符号链接:

sudo rm -f /etc/localtime

确定要配置的时区并创建符号链接:

sudo ln -s /usr/share/zoneinfo/Europe/Ljubljana /etc/localtime

我们可以通过列出“/etc/localtime”文件或者发出“ date”命令来确认更改:

date
Mon Mar 11 22:55:04 CET 2019