Configuring the Linux clock

A problem often reported by users in Linux forums is that the time displayed by the system clock is incorrect. Typically the problem is that it displays UTC instead of local time. The most common cause is incorrect configuration, although dual booting with Windows will also change the Linux system clock’s time unless either a) Linux is configured to use local time for the hardware clock, or b) Windows is configured to use UTC* and Windows’ time synchronisation with an Internet time server is disabled.

* A change to the Windows Registry is required in order to enable Windows to use UTC for hardware clock time, but even then you may still face problems (see e.g. Force Windows 8 to use UTC when dealing with BIOS clock).

Some terms you need to know: ‘hardware clock’, ‘RTC’ (real-time clock), ‘CMOS clock’ and ‘BIOS clock’ are terms commonly used for the same thing. The hardware clock is non-volatile. ‘system clock’ is the software clock the operating system uses. It is volatile (it is in the kernel). The system clock is normally set from the hardware clock when the operating system boots, taking into account various configuration options. I recommend that you read the manual for the hwclock command, as it explains in detail about clocks in Linux:

# man hwclock

To configure your time zone and clocks correctly, follow the steps below.

If your installation uses the OpenRC init system

  1. Set the time zone:

    1. Specify your time zone in the file /etc/timezone. If you are in Spain, for example, the contents of that file should be ‘Europe/Madrid‘ (without the quotes).

      # nano /etc/timezone

      You can find out which time zones are available by looking in the directory /usr/share/zoneinfo/ and its sub-directories.

    2. Provide the information for your time zone. If you are in Spain, for example, you would enter the following command:

      # cp /usr/share/zoneinfo/Europe/Madrid /etc/localtime

      Note: Some people recommend making /etc/localtime a symlink rather than creating it by copying a file from /usr/share/zoneinfo/, however I recommend copying. You should definitely not use a symlink if /usr is on a different partition (see Ref. 1).

  2. Set the system clock’s time to your local time now (I’ll assume it is 23:54:30 on 21 September 2014 when you press Enter):

    # date 092123542014.30

  3. Specify whether the hardware clock time is UTC:

    # hwclock --utc

    or local time:

    # hwclock --localtime

    It is preferable for the hardware clock time to be in UTC. However, if you dual boot with Windows it is recommended for the hardware clock time to be in local time rather than UTC unless both the following are true: a) the Windows Registry has been configured for hardware clock time in UTC; b) Windows’ time synchronisation with an Internet time server is disabled.

  4. Set the hardware clock’s time by specifying your local time (I’ll assume it is 23:54:50 on 21 September 2014 when you press Enter):

    # rm /etc/adjtime
    # hwclock --set --date="2014-09-21 23:54:50"

    Note: You must specify local time in the above command, even if you intend the hardware clock time to be UTC.

    Note that the third line in /etc/adjtime should be ‘UTC’ if the hardware clock time is in UTC, or ‘LOCAL’ if the hardware clock time is in local time. For example:

    # cat /etc/adjtime
    0.000000 1412038530 0.000000
    1412038530
    UTC

  5. Tell OpenRC whether the hardware clock uses UTC or local time, and to update the hardware clock time from the system clock time at every shutdown (taking into account any time zone difference between the two clocks):

    # nano /etc/conf.d/hwclock

    1. Make clock="UTC" (or clock="local" if you dual boot with Windows and the Windows Registry is not configured to use UTC for hardware clock time).

    2. Make clock_systohc="YES" to adjust the hardware clock time at shutdown based on the software clock time (taking time zone into account). However, you don’t need to bother doing this if your kernel configuration has CONFIG_RTC_SYSTOHC=y and your installation is configured to synchronise the system clock with a NTP time server (see my post Synchronise your Gentoo Linux clock with an Internet time server). You can check if the hardware clock time is being updated from the software clock time (taking time zone into account) by looking at the kernel messages displayed when in verbose mode during shutdown to see if the following message is displayed:

      Setting hardware clock using the system clock [UTC] ...

    3. Make clock_hctosys="YES" to adjust the system clock time at start up based on the hardware clock time (taking time zone into account). However, you don’t need to bother doing this if your kernel configuration has CONFIG_RTC_HCTOSYS=y. You can check by looking at the kernel messages displayed when in verbose mode during boot to see if the following message is displayed:

      Setting system clock using the hardware clock [UTC] ...

  6. Reboot and check everything is working as expected:

    # date
    Tue 30 Sep 01:55:55 BST 2014
    # hwclock
    Tue 30 Sep 2014 01:55:59 BST -0.031877 seconds

    The hwclock command always shows local time, even if you keep your hardware clock in UTC.

  7. Optionally (but I recommend it), configure your installation to synchronise the system clock with an Internet NTP server (see my post Synchronise your Gentoo Linux clock with an Internet time server).

If your installation uses systemd

  1. Set the time zone:

    1. Find out the available time zones:

      # timedatectl list-timezones

    2. Specify your time zone (I’ll assume you are in Spain in this example):

      # timedatectl set-timezone Europe/Madrid

  2. Set the system clock time to your local time (I’ll assume it is 23:54:30 on 21 September 2014 when you press Enter):

    # timedatectl set-time "2014-09-21 23:54:30"

  3. Inform systemd that the hardware clock uses UTC, and set the current UTC in the hardware clock now:

    # timedatectl set-local-rtc 0

    Note that, by default, systemd assumes the hardware clock uses UTC. Although systemd can be configured to assume the hardware clock uses local time, for technical reasons it is not recommended (see man timedatectl and Arch Wiki article Time for an explanation of why this is not advisable).

    Note that the third line in /etc/adjtime should be ‘UTC’ if the hardware clock time is in UTC, or ‘LOCAL’ if the hardware clock time is in local time. For example:

    # cat /etc/adjtime
    0.000000 1412038530 0.000000
    1412038530
    UTC

  4. Reboot and check everything is working as expected:

    $ timedatectl

  5. Optionally (but I recommend it), configure your installation to synchronise the system clock with an Internet NTP server (see my post Synchronising the clock using NTP in Sabayon Linux).

References

[1] Gentoo Forums – how exactly to set timezone in /etc/localtime ?[solved]

Synchronising the clock using NTP in Sabayon Linux

In my previous post I explained how to install Sabayon Linux via the command line from the Sabayon Linux ‘SpinBase’ ISO.

If the system clock in your current installation is not being synchronised with an external time server over the Internet, the simplest way to achieve this is to install the net-misc/ntp package and configure systemd as shown below.

Note that I use net-misc/ntp rather than net-misc/chrony because the latter does not work in my Sabayon Linux installation; after I have configured the Chrony daemon, the command ‘systemctl status chronyd‘ returns the error message ‘Can’t initialise from real time clock, driver not loaded’. Of course, if Chrony happens to be installed and is working fine, you don’t need to do anything at all. But if Chrony is not working correctly and you want to try the ntp daemon instead, before performing the steps below you’ll first need to disable Chrony as explained under ‘Caveat’ at the end of this post.

  1. Install the ntp package:

    # equo install ntp

  2. Enable the ntp daemon so that it starts at boot:

    # systemctl enable ntpd
    # timedatectl set-ntp true

  3. Start the ntp daemon running now:

    # systemctl start ntpd

  4. Check whether the daemon is running:

    # systemctl status ntpd

Below I show the console output for the complete sequence from Step 2 to Step 4 with the command ‘timedatectl status‘ between each step so that you can see the effect. Note that I had previously set the hardware clock time (which, by default, systemd assumes to be UTC) to be the same time as local time. Since BST and UTC do not coincide, clearly both clocks should not both contain 10:06, so watch what happens below once the NTP daemon is launched.

sabayon fitzcarraldo # timedatectl status
      Local time: Mon 2014-09-22 10:06:06 BST
  Universal time: Mon 2014-09-22 09:06:06 UTC
        RTC time: Mon 2014-09-22 10:06:07
        Timezone: Europe/London (BST, +0100)
     NTP enabled: no
NTP synchronized: no
 RTC in local TZ: no
      DST active: yes
 Last DST change: DST began at
                  Sun 2014-03-30 00:59:59 GMT
                  Sun 2014-03-30 02:00:00 BST
 Next DST change: DST ends (the clock jumps one hour backwards) at
                  Sun 2014-10-26 01:59:59 BST
                  Sun 2014-10-26 01:00:00 GMT
sabayon fitzcarraldo # systemctl enable ntpd
ln -s '/usr/lib/systemd/system/ntpd.service' '/etc/systemd/system/multi-user.target.wants/ntpd.service'
sabayon fitzcarraldo # timedatectl status
      Local time: Mon 2014-09-22 10:06:39 BST
  Universal time: Mon 2014-09-22 09:06:39 UTC
        RTC time: Mon 2014-09-22 10:06:39
        Timezone: Europe/London (BST, +0100)
     NTP enabled: no
NTP synchronized: no
 RTC in local TZ: no
      DST active: yes
 Last DST change: DST began at
                  Sun 2014-03-30 00:59:59 GMT
                  Sun 2014-03-30 02:00:00 BST
 Next DST change: DST ends (the clock jumps one hour backwards) at
                  Sun 2014-10-26 01:59:59 BST
                  Sun 2014-10-26 01:00:00 GMT
sabayon fitzcarraldo # timedatectl set-ntp true
sabayon fitzcarraldo # timedatectl status
      Local time: Mon 2014-09-22 10:06:57 BST
  Universal time: Mon 2014-09-22 09:06:57 UTC
        RTC time: Mon 2014-09-22 10:06:58
        Timezone: Europe/London (BST, +0100)
     NTP enabled: yes
NTP synchronized: no
 RTC in local TZ: no
      DST active: yes
 Last DST change: DST began at
                  Sun 2014-03-30 00:59:59 GMT
                  Sun 2014-03-30 02:00:00 BST
 Next DST change: DST ends (the clock jumps one hour backwards) at
                  Sun 2014-10-26 01:59:59 BST
                  Sun 2014-10-26 01:00:00 GMT
sabayon fitzcarraldo # systemctl start ntpd
sabayon fitzcarraldo # timedatectl status
      Local time: Mon 2014-09-22 10:07:13 BST
  Universal time: Mon 2014-09-22 09:07:13 UTC
        RTC time: Mon 2014-09-22 09:07:13
        Timezone: Europe/London (BST, +0100)
     NTP enabled: yes
NTP synchronized: yes
 RTC in local TZ: no
      DST active: yes
 Last DST change: DST began at
                  Sun 2014-03-30 00:59:59 GMT
                  Sun 2014-03-30 02:00:00 BST
 Next DST change: DST ends (the clock jumps one hour backwards) at
                  Sun 2014-10-26 01:59:59 BST
                  Sun 2014-10-26 01:00:00 GMT
sabayon fitzcarraldo # systemctl status ntpd
ntpd.service - Network Time Service
   Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled)
   Active: active (running) since Mon 2014-09-22 10:07:11 BST; 23s ago
 Main PID: 2420 (ntpd)
   CGroup: /system.slice/ntpd.service
           └─2420 /usr/sbin/ntpd -g -n

Sep 22 10:07:11 sabayon ntpd[2420]: Listen normally on 5 eth0 fe80::a00:27ff:fe86:21f3 UDP 123
Sep 22 10:07:11 sabayon ntpd[2420]: peers refreshed
Sep 22 10:07:11 sabayon ntpd[2420]: Listening on routing socket on fd #22 for interface updates
Sep 22 10:07:13 sabayon ntpd[2420]: Deferring DNS for 0.gentoo.pool.ntp.org 1
Sep 22 10:07:14 sabayon ntpd[2420]: Deferring DNS for 1.gentoo.pool.ntp.org 1
Sep 22 10:07:15 sabayon ntpd[2420]: Deferring DNS for 2.gentoo.pool.ntp.org 1
Sep 22 10:07:16 sabayon ntpd[2420]: Deferring DNS for 3.gentoo.pool.ntp.org 1
Sep 22 10:07:18 sabayon ntpd_intres[2422]: DNS 0.gentoo.pool.ntp.org -> 85.236.36.4
Sep 22 10:07:18 sabayon ntpd_intres[2422]: DNS 1.gentoo.pool.ntp.org -> 78.46.197.35
Sep 22 10:07:18 sabayon ntpd_intres[2422]: DNS 2.gentoo.pool.ntp.org -> 91.234.160.19
sabayon fitzcarraldo #

Notice that the NTP daemon synchronised the RTC (hardware clock) time to UTC (I had previously set the hardware clock time to be the same as local time to show what would happen when the NTP deamon was launched). That is correct: notice ‘RTC in local TZ: no‘ in the output above, meaning that systemd by default assumes the time in the RTC is UTC.

By the way, in case you’re wondering, the NTP daemon of course synchronises the time in the system clock too. You do not need to worry: the system clock uses the local time of the time zone you previously configured (see my previous post), so the Linux date command and the clock of the Desktop Environment will show you local time by default.

Caveat
Note that I am using the ntp daemon instead of the Chrony daemon or the OpenNTPD daemon. If Chrony happens to be installed and active in your Sabayon Linux installation, before performing any of the above steps you’ll first need to do the following:

  1. Uninstall the Chrony package:

    # equo remove chrony

  2. Disable the Chrony daemon so that it does not start at boot:

    # systemctl disable chronyd
    # timedatectl set-ntp false

  3. Stop the Chrony daemon running now:

    # systemctl stop chronyd

  4. Check whether the daemon is still running:

    # systemctl status chronyd

Synchronise your Gentoo Linux clock with an Internet time server

There are a number of ways to synchronise Gentoo Linux with a time server on the Internet. Here I look at a few alternatives.

ntp-client

ntp-client and the NTP daemon ntpd are installed when you install the package net-misc/ntp. Although I have read on some Web sites that /etc/init.d/ntp-client should be added to the default runlevel in order to read the time from an NTP server (once-only, during start-up), this in fact does not work because usually the network connection is not up by the time the ntp-client initscript runs. Bear in mind that ntp-client does not run continuously; it syncs once with an external time server if there is a network connection, and that’s it.

NetworkManager Dispatcher

If you are using NetworkManager, an elegant solution is to use NetworkManagerDispatcher to restart ntp-client in order to resync your system clock every time a network connection comes up. This is my favoured solution for laptops; see further on for how to configure your machine to do this.

cronjob

Another way would be to create a cronjob to run periodically the ‘/etc/init.d/ntp-client restart‘ command or the ‘ntpd -q‘ command (the -q option means “set the time and quit”).

Wait a while after start up

A ‘quick-and-dirty’ method, which I have used sometimes to synchronise a laptop’s system clock every time it boots, would be to delay running ntp-client until the network is up by putting e.g. the command below in a file 10_ntp-client.start in the directory /etc/local.d/ (10 seconds is usually enough time for a wired or wireless connection to my home network to be established):

#!/bin/bash
sleep 10s && /etc/init.d/ntp-client restart

Don’t forget to make it executable:

# chmod 744 /etc/local.d/10_ntp-client.start

NTP daemon

Regarding the NTP daemon, it is possible to configure this from the command line, rather than via a Desktop Environment GUI, to run at start-up and continue running to adjust your system clock. The command:

# rc-update add ntpd default

will add the daemon’s initscript to the default runlevel so that it is launched automatically at the next startup, and the command:

# /etc/init.d/ntpd start

will start the daemon running right now.

Note that, by default, the NTP daemon won’t correct, all in one go, a time difference between your system clock and the remote NTP server if that difference is above a certain size. However, if you want to override the default behaviour, i.e. allow the NTP daemon to make a large first adjustment to the system clock, you can set the environment variable NTPD_OPTS in the file /etc/conf.d/ntpd as follows:

NTPD_OPTS="-g"
# The -g option enables ntpd to make large adjustments.

This would mean that you would not need to run ntp-client before ntpd. However, if you run ntp-client automatically — either once after start-up or periodically — then that would be good enough for the typical Desktop user, and could be an alternative to having a continuously-running NTP daemon. Nothing stops you doing both if you want, of course.

Updating the hardware clock

If you make clock_systohc="YES" in the file /etc/conf.d/hwclock then the time in the system clock will be written to the BIOS (CMOS) clock (a.k.a. hardware clock) when you shut down your PC.

How to configure NetworkManager Dispatcher to synchronise the system clock only when a network connection is made

If you’re using a machine that is permanently connected to a network, running the NTP daemon makes sense. But what if you have a machine that is not always connected to a network when it is powered up? I have a laptop and I don’t want the NTP daemon running all the time. But I would like my laptop to synchronise with an external time server once after start up when I connect to the Internet. NetworkManager has a handy tool called NetworkManager Dispatcher for doing just this.

If you have installed NetworkManager, you’ll find there is an initscript /usr/portage/net-misc/networkmanager/files/NetworkManagerDispatcher. Copy it to the directory /etc/init.d/ and give it the necessary restrictive permissions:

# cp /usr/portage/net-misc/networkmanager/files/NetworkManagerDispatcher /etc/init.d/
# chmod 744 NetworkManagerDispatcher

You no longer need to perform the above step regarding a NetworkManagerDispatcher initscript. See my update of September 23, 2014 at the bottom of this post.

Then create a shell script called e.g. 99_ntp-client in the directory /etc/NetworkManager/dispatcher.d/ to be run by NetworkManagerDispatcher when a network connection is established, containing the following code:

#!/bin/bash

INTERFACE=$1 # The interface which is brought up or down
STATUS=$2 # The new state of the interface

case "$STATUS" in
    'up') # $INTERFACE is up
        echo "System time before starting ntp-client:" > /home/fitzcarraldo/ntp-client.txt
        date >> /home/fitzcarraldo/ntp-client.txt
        echo "Starting ntp-client:" >> /home/fitzcarraldo/ntp-client.txt
        rc-config restart ntp-client &>> /home/fitzcarraldo/ntp-client.txt
        echo "System time after starting ntp-client:" >> /home/fitzcarraldo/ntp-client.txt
        date >> /home/fitzcarraldo/ntp-client.txt
        ;;
    'down') # $INTERFACE is down
        # Check for active interface and down if no one active
        if [ ! `nm-tool|grep State|cut -f2 -d' '` = "connected" ]; then
                echo "Stopping ntp-client at:" > /home/fitzcarraldo/ntp-client.txt
                date >> /home/fitzcarraldo/ntp-client.txt
                rc-config stop ntp-client &>> /home/fitzcarraldo/ntp-client.txt
        fi
        ;;
esac

Make the root user the owner of the script, and only allow the root user to write to it and execute it:

# cd /etc/NetworkManager/dispatcher.d/
# chown root:root 99_ntp-client
# chmod 744 99_ntp-client

Then add NetworkManagerDispatcher to the default runlevel so that it will be launched every time you boot your machine:

# rc-update add NetworkManagerDispatcher default

You no longer need to perform the above step regarding a NetworkManagerDispatcher initscript. See my update of September 23, 2014 at the bottom of this post.

As the package net-misc/ntp installs both /etc/init.d/ntpd and /etc/init.d/net-client, users could optionally add the NTP daemon ntpd to the default runlevel too if desired, which would provide continuous, incremental adjustments to the system clock once net-client has done its one-shot adjustment each time a network comes up:

# rc-update add ntpd default

But users who don’t leave their PCs on for days on end — or who use laptops — can ignore the above step and just stick with the NetworkManagerDispatcher and net-client solution, whereas users who leave their machines on for days or weeks on end can also use the NTP daemon to keep the system clock in sync in between the times when ntp-client has synchronised.

Don’t forget to delete ntp-client from the start-up level if you are using NetworkManagerDispatcher to run it:

# rc-update del ntp-client

Notice that the script /etc/NetworkManager/dispatcher.d/99_ntp-client logs some information in a text file ntp-client.txt in my home directory which I can check. Here is an example of what ntp-client.txt contains after I select a network (or it is selected automatically) following start up of my laptop:

System time before starting ntp-client:
Sun Jun 3 19:24:08 BST 2012
Starting ntp-client:
Restarting init script
* Setting clock via the NTP client 'ntpd' ...ntpd: time slew +0.067178s
[ ok ]
System time after starting ntp-client:
Sun Jun 3 19:24:17 BST 2012

As you can see above, the ntpd command was executed once by NetworkManagerDispatcher and made a small adjustment to the system time on my laptop.

Replacing ntpdate with ntpd in ntp-client

Just for the fun of it, I changed /etc/conf.d/ntp-client to use the command ntpd instead of ntpdate, even though the ntpdate command works fine. Anyway, here’s my /etc/conf.d/ntp-client file these days:

NTPCLIENT_CMD="ntpd"
NTPCLIENT_OPTS="-g -q"

I have added the -g option so that the ntpd command can make large adjustments to the system time if it is way off the actual time. This is useful at the beginning and end of Daylight Saving Time, or if you dual boot with Windows. Here is an example of the former when I powered up my laptop the morning after the clocks changed from BST to GMT at the end of Summer 2010:

$ cat /home/fitzcarraldo/ntp-client.txt
System time before starting ntp-client:
Sun Oct 31 09:37:23 GMT 2010
Starting ntp-client:
Starting init script
* Setting clock via the NTP client 'ntpd'...ntpd: time set -3600.122381s
[ ok ]
System time after starting ntp-client:
Sun Oct 31 08:37:30 GMT 2010

You can specify the NTP server or NTP server pool in the file /etc/ntp.conf, but the default server pool already specified in that file should work. Note again that, when ntpd is run with the -q option, it synchronises the system clock once and terminates, i.e. it is not running as a daemon.

UPDATE (September 23, 2014): Things have become easier since I wrote the above post. These days it is no longer necessary to create a NetworkManagerDispatcher initscript; you just need to put the shell script you want NetworkManagerDispatcher to execute into the directory /etc/NetworkManager/dispatcher.d/, give it attributes and permissions as shown in this post, and NetworkManager will take care of everything.

Follow

Get every new post delivered to your Inbox.

Join 51 other followers