- How to Fix Time Differences in Ubuntu 16.04 & Windows 10 Dual Boot
- Windows и UTC время в BIOS.
- Почему сбивается время компьютера (сервера) с Windows после выключения / перезагрузки
- Не сохраняется время из-за севшей батарейка BIOS
- Настройки часового пояса и синхронизации времени с time.windows.com
- Синхронизация времени в домене Windows
- Сбивается время при переключении между Linux и Windows (Dual Boot)
- Сбивается время после перезагрузки на серверах HP с Windows Server
- System time
- Contents
- Hardware clock
- Read hardware clock
- Set hardware clock from system clock
- System clock
- Read clock
- Set system clock
- Time standard
- UTC in Microsoft Windows
- Historical notes
- UTC in Ubuntu
- Time zone
- Setting based on geolocation
- Update timezone every time NetworkManager connects to a network
- Time skew
- Time synchronization
- Per-user/session or temporary settings
- Troubleshooting
- Clock shows a value that is neither UTC nor local time
- Tips and tricks
- fake-hwclock
How to Fix Time Differences in Ubuntu 16.04 & Windows 10 Dual Boot
For users who dual boot Ubuntu 16.04 and Windows, you may find the clock time is off that causes time differences after you reboot and switch between the two systems. Here’s how to fix it.
Ubuntu maintains the hardware clock (RTC, real time clock) in universal time (UTC) by default while Windows maintains the clock in local time, thus causing time conflicts between Ubuntu and Windows.
To fix it, either set Ubuntu to maintain RTC in local time or make Windows uses UTC.
1. Disable UTC and use Local Time in Ubuntu:
In previous Ubuntu editions, you can edit the config file /etc/default/rcS to disable UTC.
In Ubuntu 16.04, open terminal (Ctrl+Alt+T) and run the command below instead:
To check out if your system uses Local time, just run:
you’ll the local time zone is in use in the Warning section.
Finally restart and switch to Windows, adjust system clock time if need and done.
2. Make MicroSoft Windows uses UTC:
Another way to fix this issue is doing the following changes in Windows, Windows 10, in the case below:
1.) First if you’ve switched to local time in Ubuntu, run command in Ubuntu terminal to use back UTC:
2.) Restart and select boot into Windows 10, when you’re in, do:
- go to Start Menu, search for and launch cmd as Administrator.
- When the command console opens, paste below command to create a DWORD value to the registry:
For 64-bit Windows, use a QWORD value instead:
Windows и UTC время в BIOS.
Жизнь — такая штука, что иногда случаются вещи, которые не хотелось, чтобы случались. От таких вещей никто не застрахован и однажды это случилось со мной — для работы пришлось временно установить Windows 7 на свой собственный домашний компьютер. Нельзя сказать, что я мало знаком с этой операционной системой, однако свой домашний ПК последние пару лет держал чистым от нее. Честно говоря, она работает несколько медленнее, чем я ожидал, но плевки в сторону Windows — низость и я не буду этим заниматься. Расскажу лишь об одной из вещей, которые меня удивили, а именно, о том, что время в Windows = время в BIOS и Windows всегда меняет время BIOS при изменении своего времени.
Опишу на примере. В моем Linux установлен часовой пояс Europe/Moscow, в BIOS время — UTC. Таким образом, Linux прибавляет 3 часа к времени BIOS для получения локального времени. Конечно, я мог и в BIOS установить сразу локальное время, но мне так привычнее. После установки Windows я установил свой часовой пояс и после перезагрузки обнаружил, что Windows изменила время в BIOS на локальное. Что бы я ни делал, Windows меняла время BIOS на локальное и, в итоге, Linux показывал на 3 часа больше. Передо мной встал выбор — перенастроить Linux на UTC или перевести часы в Windows на 3 часа назад. Конечно, я выбрал второй вариант! 😉 Но друг поделился одним способом и этой глупости удалось избежать.
Чтобы Windows считала время BIOS за UTC, необходимо внести изменения в реестр и отключить синхронизацию часов с Интернет. Для этого, нужно создать *.reg файл:
После применения его к реестру, Windows перестанет изменять то, что ей изменять не положено 🙂 Проверено на Windows 7.
Почему сбивается время компьютера (сервера) с Windows после выключения / перезагрузки
В этой статье рассмотрим, почему после выключения или перезагрузки ноутбука / компьютера / сервера в операционной системе могут сбрасываться текущие настройки даты и времени, указанные ранее. Рассмотрим, как самый банальный случая с севшей батарейкой BIOS, так и более интересные кейсы с мультизагрузкой Windows и Linux на одном компьютере, и багом прошивки на Windows серверах HPE ProLiant G9 /G8.
Не сохраняется время из-за севшей батарейка BIOS
Самый «классический» ответ на вопрос «Почему не сохраняется и сбивается время и дата на компьютере?» — севшая батарейка BIOS. Данная батарейка отвечает за сохранение настроек BIOS/ UEFI, когда ваш компьютер/ноутбук выключен из розетки, а также обеспечивает автономную работу встроенных аппаратных часов.
Если батарейка села, то при отключении питания материнской карты, BIOS не может сохранить свои настройки, и все они сбрасываются, в том числе и текущее дата и время. Если ваш компьютер довольно старый, вероятность того, что у вас села батарейка крайне велика. Настоятельно рекомендуем ее заменить. Сделать это не сложно, и, как правило, особых инженерных навыков процесс замены батарейки BIOS не требует. В большинстве домашних систем используется в BIOS стандартная батарейка CR2032 на 3 вольта.
Если замена батарейки не помогла, проверьте состояние перемычки сброса настроек BIOS (джампер с перемычкой расположен рядом с отсеком для батарейки и может быть подписан как CCMOS / CLEAR / RESET). Возможно кто-то оставил данный джампер в положении «сброса», в результате чего при каждой подачи питания на мат.плату, настройки BIOS обнуляются. Верните джампер в нормальное положение.
Следующий вариант – обновление прошивки BIOS материнской карты (как это сделать – смотрите на сайте производителя вашего железа). Часто в более новых прошивках исправляются различные баги.
Настройки часового пояса и синхронизации времени с time.windows.com
В том случае, если у вас постоянно меняются настройки даты//времени в Windows, в первую очередь стоит проверить текущие настройки часового пояса и параметры синхронизации времени с интернетом. В Windows 10 текущие настройки времени можно посмотреть в меню панели инструментов (Панель управления\Часы, язык и регион -> Дата и время). В этом примере видно, что указан часовой пояс UTC + 03, переход на зимнее время отключен.
Совет . Вы можете управлять часовым поясом Windows из командой строки с помощью утилиты tzutil .
Если ваш компьютер не в домене, проверьте настройки синхронизации времени с внешним источником времени (сервером времени NTP). В этом случае в этом же окне щелкните по вкладке «Время по Интернету» и проверьте, что компьютер настроен на автоматическую синхронизацию времени с сервером time.windows.com.
Совет . Напомню, что с 2014 года в России отменен переход на летнее время. Возможно вы давно не обновляли свою ОС (Windows 8 и ниже) и у вас не установлены обновления, отключающие переход на летнее время .
Синхронизация времени в домене Windows
Если ваш компьютер входит в состав домена Active Directory, то информацию о том как работает синхронизация времени в домене можно получить из этой статьи.
Сбивается время при переключении между Linux и Windows (Dual Boot)
Отдельно стоит рассмотреть конфигурации, когда на компьютере установлены две операционные системы (Windows и Linux) в конфигурации двойной загрузки (Dual Boot). Вы можете столкнуться с проблемой, что после переключения между операционными системами (загрузки в Linux после Windows) сбивается время на несколько часов вперед или назад.
Windows и Linux по разному работают с временем BIOS. Дело тут в наличии двух форматов представления времени UTC и localtime .
Операционные системы GNU/Linux (в том числе Mac OS X) считают, что время в BIOS указано в формате UTC (по Гринвичу). Соответственно, при загрузке Linux для преобразования UTC к локальному времени добавляет (отнимает) смещение текущего часового пояса, который выбрал пользователь. Т.е. чтобы получить локальное время для часового пояса Москвы UTC+3, Linux добавит 3 часа.
Windows же считает, что в время в BIOS хранится в формате localtime, и если вы указали новый часовой пояс, или синхронизировали время с внешним источником, система соответственным образом меняет время в BIOS на локальное время. Linux (Ubuntu в моем случае) считает, что время в BIOS указано в формате UTC и дополнительно добавляет смещение часового пояса. Именно поэтому и сбивается время при переключении между Linux и Windows.
Чтобы исправить такую ситуацию, нужно переключить Windows на использование времени в формате UTC с помощью параметра реестра RealTimeIsUniversal .
reg add «HKLMACHINE\System\CurrentControlSet\Control\TimeZoneInformation» /v RealTimeIsUniversal /t REG_DWORD /d 1 /f
Совет. В 64 битных версиях Windows нужно создавать параметр типа QWORD вместо DWORD: reg add HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation /v RealTimeIsUniversal /t REG_QWORD /d 1
Также в Windows нужно отключить обновление времени из Интернета, т.к. служба времени Windows при каждом обновлении времени будет сбрасывать UTC время на локальное.
sc config w32time start= disabled
Осталось перезагрузить Windows.
Либо можно переключить Linux на использование локального времени. В Ubuntu 15.04 и выше это можно сделать командой:
timedatectl set-local-rtc 1
Сбивается время после перезагрузки на серверах HP с Windows Server
На серверах HPE DL/ML Gen9 с Windows Server 2008 R2 / 2012 R2 у одного из удаленных заказчиков столкнулись с интересной проблемой после смены часового пояса. Как оказалось, на серверах HP ProLiant Gen9 (и на одном из серверов HP ProLiant DL580 Gen8) при изменении системного времени или часового пояса, после перезагрузки сервера, системное время не сохранялось и сбрасывалось на предыдущее. Проблема были подвержены сервера, в которых Windows Server загружается в режиме Legacy (при нативной UEFI загрузки проблемы отката времени не было).
В журнале системы при этом появлялось такое событие:
The system time has changed to 2018-04-29T12:12:28.500000000Z from 2018-04-29T13:12:27.923115700Z.
Change Reason: System time synchronized with the hardware clock.
В качестве решения проблемы HP предлагает обновить ROM до версии не менее 1.5. Именно в этой версии ROM-Based Setup Utility (RBSU) не подвержена багу со сбросом временм.
Либо в качестве обходного решения, можно указать, чтобы Windows считала, что BIOS отдает ей системное время в формате UTC (а не локальное время). Для этого, как мы уже говорили выше нужно создать в ключе реестра HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation параметр с именем RealTimeIsUniversal и значением 1.
System time
This article or section needs expansion.
In an operating system, the time (clock) is determined by four parts: time value, whether it is local time or UTC or something else, time zone, and Daylight Saving Time (DST) if applicable. This article explains what they are and how to read/set them. Two clocks are present on systems: a hardware clock and a system clock which are also detailed in this article.
Standard behavior of most operating systems is:
- Set the system clock from the hardware clock on boot.
- Keep accurate time of the system clock, see #Time synchronization.
- Set the hardware clock from the system clock on shutdown.
Contents
Hardware clock
The hardware clock (a.k.a. the Real Time Clock (RTC) or CMOS clock) stores the values of: Year, Month, Day, Hour, Minute, and Seconds. Only 2016, or later, UEFI firmware has the ability to store the timezone, and whether DST is used.
Read hardware clock
Set hardware clock from system clock
The following sets the hardware clock from the system clock. Additionally it updates /etc/adjtime or creates it if not present. See hwclock(8) section «The Adjtime File» for more information on this file as well as the #Time skew section.
System clock
The system clock (a.k.a. the software clock) keeps track of: time, time zone, and DST if applicable. It is calculated by the Linux kernel as the number of seconds since midnight January 1st 1970, UTC. The initial value of the system clock is calculated from the hardware clock, dependent on the contents of /etc/adjtime . After boot-up has completed, the system clock runs independently of the hardware clock. The Linux kernel keeps track of the system clock by counting timer interrupts.
Read clock
To check the current system clock time (presented both in local time and UTC) as well as the RTC (hardware clock):
Set system clock
To set the local time of the system clock directly:
sets the time to May 26th, year 2014, 11:13 and 54 seconds.
Time standard
There are two time standards: localtime and Coordinated Universal Time (UTC). The localtime standard is dependent on the current time zone, while UTC is the global time standard and is independent of time zone values. Though conceptually different, UTC is also known as GMT (Greenwich Mean Time).
The standard used by the hardware clock (CMOS clock, the BIOS time) is set by the operating system. By default, Windows uses localtime, macOS uses UTC, and UNIX-like systems vary. An OS that uses the UTC standard will generally consider the hardware clock as UTC and make an adjustment to it to set the OS time at boot according to the time zone.
If multiple operating systems are installed on a machine, they will all derive the current time from the same hardware clock: it is recommended to adopt a unique standard for the hardware clock to avoid conflicts across systems and set it to UTC. Otherwise, if the hardware clock is set to localtime, more than one operating system may adjust it after a DST change for example, thus resulting in an over-correction; problems may also arise when traveling between different time zones and using one of the operating systems to reset the system/hardware clock.
The hardware clock can be queried and set with the timedatectl command. You can see the current hardware clock time standard of the Arch system using:
To change the hardware clock time standard to localtime, use:
To revert to the hardware clock being in UTC, type:
These generate /etc/adjtime automatically and update the RTC accordingly; no further configuration is required.
During kernel startup, at the point when the RTC driver is loaded, the system clock may be set from the hardware clock. Whether this occurs depends on the hardware platform, the version of the kernel and kernel build options. If this does occur, at this point in the boot sequence, the hardware clock time is assumed to be UTC and the value of /sys/class/rtc/rtcN/hctosys (N=0,1,2. ) will be set to 1.
Later, the system clock is set again from the hardware clock by systemd, dependent on values in /etc/adjtime . Hence, having the hardware clock using localtime may cause some unexpected behavior during the boot sequence; e.g system time going backwards, which is always a bad idea (there is a lot more to it). To avoid it systemd will only synchronize back, if the hardware clock is set to UTC and keep the kernel uninformed about the local timezone. As a consequence timestamps on a FAT filesystem touched by the Linux system will be in UTC.
UTC in Microsoft Windows
To dual boot with Windows it is recommended to configure Windows to use UTC, rather than Linux to use localtime. (Windows by default uses localtime [1].)
It can be done by a simple registry fix: Open regedit and add a DWORD value for 32-bit Windows, or QWORD for 64-bit one, with hexadecimal value 1 to the registry:
You can do this from an Administrator Command Prompt running:
(Replace QWORD with DWORD for 32-bit Windows.)
Alternatively, create a *.reg file (on the desktop) with the following content and double-click it to import it into registry:
(Replace qword with dword for 32-bit Windows.)
Should Windows ask to update the clock due to DST changes, let it. It will leave the clock in UTC as expected, only correcting the displayed time.
The #Hardware clock and #System clock time may need to be updated after setting this value.
If you are having issues with the offset of the time, try reinstalling tzdata and then setting your time zone again:
Historical notes
For really old Windows, the above method fails, due to Windows bugs. More precisely,
- Before Vista SP2, there is a bug that resets the clock to localtime after resuming from the suspend/hibernation state.
- For XP and older, there is a bug related to the daylight saving time. See [2] for details.
- For even older versions of Windows, you might want to read https://www.cl.cam.ac.uk/
mgk25/mswish/ut-rtc.html — the functionality was not even documented nor officially supported then.
For these operating systems, it is recommended to use localtime.
UTC in Ubuntu
Ubuntu and its derivatives have the hardware clock set to be interpreted as in «localtime» if Windows was detected on any disk during Ubuntu installation. This is apparently done deliberately to allow new Linux users to try out Ubuntu on their Windows computers without editing the registry.
For changing this behavior, see above.
Time zone
To check the current zone defined for the system:
To list available zones:
To set your time zone:
This will create an /etc/localtime symlink that points to a zoneinfo file under /usr/share/zoneinfo/ . In case you choose to create the link manually (for example during chroot where timedatectl will not work), keep in mind that it must be a symbolic link, as specified in archlinux(7) [dead link 2021-02-08] :
Setting based on geolocation
To set the timezone automatically based on the IP address location, one can use a geolocation API to retrieve the timezone, for example curl https://ipapi.co/timezone , and pass the output to timedatectl set-timezone for automatic setting. Some geo-IP APIs that provide free or partly free services are listed below:
Update timezone every time NetworkManager connects to a network
Alternatively, the tool tzupdate AUR automatically sets the timezone based on the geolocation of the IP address. This comparison of the most popular IP geolocation apis may be helpful in deciding which API to use in production.
Time skew
Every clock has a value that differs from real time (the best representation of which being International Atomic Time); no clock is perfect. A quartz-based electronic clock keeps imperfect time, but maintains a consistent inaccuracy. This base ‘inaccuracy’ is known as ‘time skew’ or ‘time drift’.
When the hardware clock is set with hwclock , a new drift value is calculated in seconds per day. The drift value is calculated by using the difference between the new value set and the hardware clock value just before the set, taking into account the value of the previous drift value and the last time the hardware clock was set. The new drift value and the time when the clock was set is written to the file /etc/adjtime overwriting the previous values. The hardware clock can therefore be adjusted for drift when the command hwclock —adjust is run; this also occurs on shutdown but only if the hwclock daemon is enabled, hence for Arch systems which use systemd, this does not happen.
If the hardware clock keeps losing or gaining time in large increments, it is possible that an invalid drift has been recorded (but only applicable, if the hwclock daemon is running). This can happen if you have set the hardware clock time incorrectly or your time standard is not synchronized with a Windows or macOS install. The drift value can be removed by first removing the file /etc/adjtime , then setting the correct hardware clock and system clock time. You should then check if your time standard is correct.
The software clock is very accurate but like most clocks is not perfectly accurate and will drift as well. Though rarely, the system clock can lose accuracy if the kernel skips interrupts. There are some tools to improve software clock accuracy:
Time synchronization
The Network Time Protocol (NTP) is a protocol for synchronizing the clocks of computer systems over packet-switched, variable-latency data networks. The following are implementations of NTP available for Arch Linux:
- Chrony — A client and server that is roaming friendly and designed specifically for systems that are not online all the time.
https://chrony.tuxfamily.org/ || chrony
- ConnMan — A lightweight network manager with NTP support.
https://01.org/connman || connman
- Network Time Protocol daemon — The reference implementation of the protocol, especially recommended to be used on time servers. It can also adjust the interrupt frequency and the number of ticks per second to decrease system clock drift, and will cause the hardware clock to be re-synchronised every 11 minutes.
http://www.ntp.org/ || ntp
- ntpclient — A simple command-line NTP client.
http://doolittle.icarus.com/ntpclient/ || ntpclientAUR
- NTPsec — A fork of NTPd, focused on security.
https://ntpsec.org/ || ntpsecAUR
- OpenNTPD — Part of the OpenBSD project and implements both a client and a server.
http://www.openntpd.org/ || openntpd
- sntp — An SNTP client that comes with NTPd. It supersedes ntpdate and is recommended in non-server environments.
http://www.ntp.org/ || ntp
- systemd-timesyncd — A simple SNTP daemon that only implements a client side, focusing only on querying time from one remote server. It should be more than appropriate for most installations.
https://www.freedesktop.org/wiki/Software/systemd/ || systemd
Per-user/session or temporary settings
For some use cases it may be useful to change the time settings without touching the global system values. For example to test applications relying on the time during development or adjusting the system time zone when logging into a server remotely from another zone.
To make an application «see» a different date/time than the system one, you can use the faketime (from libfaketime ) utility.
If instead you want an application to «see» a different time zone than the system one, set the TZ environment variable, for example:
This is different than just setting the time, as for example it allows to test the behavior of a program with positive or negative UTC offset values, or the effects of DST changes when developing on systems in a non-DST time zone.
Another use case is having different time zones set for different users of the same system: this can be accomplished by setting the TZ variable in the shell’s configuration file, see Environment variables#Defining variables.
Troubleshooting
Clock shows a value that is neither UTC nor local time
This might be caused by a number of reasons. For example, if your hardware clock is running on local time, but timedatectl is set to assume it is in UTC, the result would be that your timezone’s offset to UTC effectively gets applied twice, resulting in wrong values for your local time and UTC.
To force your clock to the correct time, and to also write the correct UTC to your hardware clock, follow these steps:
- Setup ntpd (enabling it as a service is not necessary).
- Set your time zone correctly.
- Run ntpd -qg to manually synchronize your clock with the network, ignoring large deviations between local UTC and network UTC.
- Run hwclock —systohc to write the current software UTC time to the hardware clock.
Tips and tricks
fake-hwclock
alarm-fake-hwclock designed especially for system without battery backed up RTC, it includes a systemd service which on shutdown saves the current time and on startup restores the saved time, thus avoiding strange time travel errors.