Time handling

First we need to understand that there are 2 clocks in your system for telling the time:

  • the system clock
  • the hardware clock

The system clock starts running when you startup your computer. It "forgets" time when you poweroff the system. The hardware clock is a backup clock that keeps running after turning off your computer. It uses a battery to power itself. The hardware clock is the one you can setup on the BIOS setup screen.

The system clock in Linux is a counter that counts the number of seconds since januari 1, 1970 12:00am UTC. The timezones UTC and GMT are almost the same thing. They differ less than one second. The exact definitions can be found on the internet.

When a Linux distro is installed, the user is asked whether the hardware clock (this is the clock which keeps running after turning off your computer, and which you can change in the BIOS setup screen) is in UTC or local time. Most users will choose local time. This prevents problems when booting Windows, and from the user's point of view, it seems more logical, because you can enter your own time on your BIOS setup screen, instead of the UTC time. Anyway, this setting (whether the hardware clock is in local or UTC time) is stored in /etc/defaults/rcS.

The timezone of local time is determined by /etc/localtime. This may be a copy or a symlink of one of the files under /usr/share/zoneinfo, for example /usr/share/zoneinfo/Europe/Amsterdam.

Now, when Linux boots, the hardware clock is read, converted to UTC (respecting the /etc/defaults/rcS and /etc/localtime files), and written to the system clock. At shutdown it goes the other way around.

When the user asks the time, the environment variable TZ is checked, which can be used to override the default timezone stored in /etc/localtime. The time read from the UTC system clock is converted to the desired timezone and printed.

Here is an example. Let's say the hardware clock is 2:00pm local time, /etc/localtime is linked to Amsterdam and we are in august, which means daylight savings time is in effect. So we are GMT+2 (GMT+1, plus 1 extra hour for DST). UTC is 2 hours behind UTC+2. UTC is 12:00pm. The system clock is set to 12:00pm. When the use asks the time it is recalculated from UTC to UTC+2, and 2:00pm is displayed.

Useful commands:

  • date to print or set the date and time. Use man date to see the manual.
  • hwclock -w to synchronize the hardware clock with the system clock. This is automatically done when shutting down the system. When using this command directly, use the --utc option if the hardware clock should be in UTC.
  • hwclock -s to read the hardware clock and set the system clock. This is automatically done when starting up the system. Again, when using this command directly, use --utc if needed.