在双系统下,主机的时间经常会发生混乱,windows以硬件时间为当前时区时间,而linux通常以硬件时间为utc时间,对于+8时区,两者相差8小时。本文介绍了linux下时间的设置和同步。
在Linux下,系统时间和硬件时间并不会自动同步。在Linux运行过程中,系统时间和硬件时间以异步的方式运行,互不干扰。硬件时间的运行,是靠BIOS电池来维持,而系统时间,是用CPU来维持的。在系统开机的时候,会自动从BIOS中取得硬件时间,设置为系统时间。
常用的时间操作命令
命令 | 功能 |
---|---|
date命令 | 查看系统时间,设置时间 |
hwclock命令 | 查看硬件时间,可以让系统时间和硬件时间的同步 |
ntpdate命令 | 可以让不同机器之间同步时间 |
系统时间设置
date
//查看系统时间
Mon Mar 17 05:45:59 PM CST 2025sudo date -s "20250316 16:00:00"
//修改系统时间(yyyymmdd hh:mm:ss)
Sun Mar 16 04:00:00 PM CST 2025
硬件时间设置
sudo hwclock
//查看硬件时间(hwclock –show 或hwclock -r也可以),需要sudo
2025-03-17 17:50:57.997658+08:00sudo hwclock --set --date "20250317 20:00:00"
//设置硬件时间
系统时间和硬件时间的同步
1 | sudo hwclock --systohc //以系统时间同步硬件时间 |
NTP服务器时间的同步
通常可以使用ntpdate命令或者ntpd服务来同步时间。
- ntpdate同步
ntpdate没有的话需要apt install ntpdate
sudo ntpdate 0.ubuntu.pool.ntp.org
//同步服务器时间
17 Mar 17:59:03 ntpdate[5663]: adjust time server 78.46.102.180 offset -0.073819 sec - 定时任务里的时间同步
在crontab中添加:每天的12点同步时间0 12 * * * /usr/sbin/ntpdate 0.ubuntu.pool.ntp.org
- ntp服务同步
1
2
3sudo apt install ntp
sudo systemctl start ntp
sudo systemctl status ntp
设置文件为/etc/ntp.conf,时间服务器已经预先设置好了。
时区设置参见:Ubuntu上修改系统时区的方法