- 获取当前时间
$ date +%Y%m%d-%H%M%S
20211014-090539
- UTC和本地时间相互转换
Local -> UTC
$ date -u|--utc
Thu Oct 14 16:07:43 UTC 2021
UTC -> Local
$ date -d 'Oct 13 22:43:00 2021 UTC'
Wed Oct 13 15:43:00 PDT 2021
这也包括任何时区转UTC或者UTC转任何时区了。
$ date -d 'Oct 13 22:43:00 2021 [TZ]' [-u]
- [TZ]: 表示“Oct 13 22:43:00 2021”所使用的时区。
-[u]: 表示输出是UTC还是Local
- 设置系统时间
$ sudo date -s "Thu Oct 14 09:36:25 PDT 2021"
还有一个简洁的调整时间的格式,非常好用:
$ sudo date --set='+2 minutes'
$ sudo date --set='-10 seconds'
分别表示推迟2分钟,和提前10秒,很好用。
- 设置硬件时间
$ clock--set --date="1/25/09 00:00"
或者用hwclock,他们其实是同一个命令。
另外把系统时间和硬件时间互相同步:
hwclock --systohc # 把系统时间 写入 硬件时间
hwclock --hctosys # 把硬件时间 写入 系统时间
- 设置ntp时间服务器
首先需要安装ntp服务包,请自行google如果安装。
- 手动同步当前时间和ntp服务器时间:
$ sudo ntpdate <NTP server>
- 自动同步
有两种自动同步方式,一是设置ntpdata的cron job让定时同步,当然这会有时间跳跃的问题,如果本地CPU tick不准确,另一种使用ntp服务自动同步。
启动和停止ntpd服务:
$ sudo systemctl start ntpd
$ sudo systemctl stop ntpd
- 查看ntp server的信息
$ ntpq -p
- 查看当前本地ntp服务的状态
$ ntpstat
- timedatectl的使用
timedatectl 是 systemd-timedated.service 系统服务的命令行客户端,用来代替date、hwclock 命令来调整时间。
- 查看当前系统的时间状态
$ timedatectl # or
$ timedatectl status
Local time: Sun 2021-10-17 23:45:20 UTC
Universal time: Sun 2021-10-17 23:45:20 UTC
RTC time: Sun 2021-10-17 23:45:20
Time zone: UTC (UTC, +0000)
NTP enabled: yes
NTP synchronized: yes
RTC in local TZ: no
DST active: n/a
- 设置时间
$ sudo timedatectl set-time '2021-10-15 16:10:10'
这个命令会同时把本地系统时间和硬件时间都修改,也就是相当于两条命令(date --set和hwclock --set)。
另外还有一个要求是"NTP enabled"的值必须是false才能修改时间,否则会报错:Failed to set time: Automatic time synchronization is enabled
- 设置ntp是否自动同步时间 (当然必须先安装ntp才能设置成自动同步)
$ sudo timedatectl set-ntp true|false
这个命令的后天会把ntpd给启动和停止,我们看$ sudo systemctl status ntpd
能发现ntpd服务的状态变化。
- 设置硬件时间是本地时间还是UTC时间
$ sudo timedatectl set-local-rtc true|false
true: 表示RTC时间的是本地时间
false: 表示RTC使用的是UTC时间
- 如何手动强制一次与ntp server做时间同步
$ sudo service ntpd stop
$ sudo ntpd -gq # or. $ sudo ntpdate <ntp server>
$ sudo service ntpd start
注意这个同步命令必须要ntpd系统服务停止状态才能运行。
另外这个同步只同步ntp server时间和本地系统时间,并不会修改本地硬件时间,还需要执行$ sudo hwclock --systohc
同步到硬件时间。
网友评论