概念
时钟
操作系统中通常存在两种时间:
- 系统时钟(system clock),也称软件时钟
- 硬件时钟(hardware clock),也称 BIOS 时间、RTC(实时时钟,real-time clock)
时间标准
-
UTC
Coordinated Universal Time(协调世界时),又称世界标准时间、国际协调时间。由于英文(CUT)和法文(TUC)的缩写不同,作为妥协,统一简称为 UTC。
UTC 由平均太阳时(以 GMT 为准)、地轴运动修正后的新时标以及以秒为单位的国际原子时所综合计算而成。
-
GMT
Greenwich Mean Time(格林尼治时间)。
GMT 规定太阳每天经过位于英国伦敦郊区的皇家格林尼治天文台的时间为中午 12 点。
UTC vs GMT
GMT 源自曾经英国的航海时代霸权,是前世界标准时间。自上世纪 70 年代,UTC 逐渐取代 GMT,成为现世界标准时间。
UTC 基于原子钟,GMT 基于天文学。UTC 考虑了地球自转每天的不规则以及其减慢的趋势,并综合了原子钟,因此更为精确。二者相差不是太大,大约有秒级别的差距。
GMT 可以作为 UTC 的同义词。GMT 也可以指代时区,此时 GMT = UTC + 0。
-
localtime
本地时间或地方时,等于所在时区内的时间,由 UTC ± 偏移量表示,例如北京时间(中国标准时间,CST)为 UTC + 8。
-
时区
从格林尼治本初子午线起,经度每向东或者向西 15°,就划分一个时区,在这个区域内,使用相同的标准时间。不过实际上,常将一个国家或一个省份划分在一起,而且一些国家会由于特定原因改变自己的时区。
全球共分为 24 个时区,相邻时区的时间相差一个小时。所有时区的详细信息可见 Time Zone Abbreviations - Worldwide List。
操作系统时间
通常,操作系统从启动到关机对于时间的处理流程为
- 启动时根据硬件时钟设置系统时钟
- 运行时通过联网同步校正系统时钟
- 关机时根据系统时钟设置硬件时钟
在硬件时钟上,Windows 默认使用 localtime,Linux / Unix / Mac 默认使用 UTC。因此 Windows + Linux 双系统会出现时间不一致问题。
Linux 时间命令
hwclock --show # 显示硬件时钟
hwclock --systohc # 同步系统时钟到硬件时钟
timedatectl # 显示系统时钟和硬件时钟
timedatectl status # 同上
timedatectl set-time "yyyy-MM-dd hh:mm:ss" # 设置系统时钟
timedatectl set-local-rtc 1 # 设置硬件时钟,1 为 localtime,0 为 UTC
timedatectl list-timezones # 显示可用时区
timedatectl set-timezone Asia/Shanghai # 设置时区
timedatectl set-ntp true # 开启联网同步系统时钟
若想根据 IP 地址自动设置时区,见系统时间 - Arch Linux 中文维基。
方法
要么让 Windows 从 localtime 到 UTC,要么让 Linux 从 UTC 到 localtime,二选一即可。
修改 Windows 时间
更改注册表,在注册表项 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation
中添加一个名为 RealTimeIsUniversal
的值,类型为 REG_DWORD
,值为 1
。
或者用命令行
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /d 1 /t REG_DWORD /f
然后禁用 Windows 时间同步功能(在设置中寻找)。
注意,对于 Win 10 以前的老版本,可能有的问题见系统时间 - Arch Linux 中文维基。
修改 Linux 时间
sudo timedatectl set-local-rtc 1
输入 timedatectl
查看状态
$ timedatectl
Local time: Thu 2024-01-18 11:04:24 CST
Universal time: Thu 2024-01-18 03:04:24 UTC
RTC time: Thu 2024-01-18 11:04:23
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
NTP service: active
RTC in local TZ: yes
Warning: The system is configured to read the RTC time in the local time zone.
This mode cannot be fully supported. It will create various problems
with time zone changes and daylight saving time adjustments. The RTC
time is never updated, it relies on external facilities to maintain it.
If at all possible, use RTC in UTC by calling
'timedatectl set-local-rtc 0'.
可以看到此时 Linux 硬件时钟(RTC time)使用 localtime。