DEV Community

Rocky Warren
Rocky Warren

Posted on • Originally published at rocky.dev on

Setting Linux System Time, Date, and Time Zone

Embedded systems sometimes require setting the system time, date, and time zone. On Linux, there are two clocks. The first is a hardware clock that is typically battery-backed and always running. The OS is in charge of the second, known as the system clock. The typical life-cycle is as follows:

  1. On Linux boot, system clock is synced to hardware clock via script in /sbin/hwclock
  2. System clock is used to keep time while OS is running
  3. On shutdown, hardware clock is synced to system clock

Time/Date

Setting the system time is straightforward. If your application happens to be in C or C++, you can use stime (preferred) or settimeofday. Note that it will likely require superuser access. You can also change it directly from the command line using the date command, date MMDDHHMMYYYY.

Running date or date --utc yields the current system time in local time and Coordinated Universal Time (UTC) respectively.

To manually sync the hardware clock to the new system clock value (rather than waiting until Linux shuts down), use the hwclock command, hwclock --systohc --utc. The --utc option indicates that the hardware clock will be stored in UTC and ensures Daylight Savings time is handled automatically by the OS. If you plan to dual boot with systems that only uses local time (like Windows), you should omit it.

Notes:

  • hwclock yields the current hardware time in local time even if the --utc option is used.
  • When /sbin/hwclock is run at OS boot to sync the system clock to the hardware clock, the hardware clock is assumed to be in local time. If you set it using --utc, set UTC=true in /etc/sysconfig/clock (file location is distribution dependent).
  • There is not a C API to accomplish this syncing so you will need to make a direct system call.

Time Zone

Linux stores time zone information at /usr/share/zoneinfo (distribution dependent). You can view the contents of these files using the zdump command (usually with the -v option).

There are two different ways to set the time zone. The easiest way (that does not require superuser access) is to set the TZ environment variable. The downside of this approach is that the time zone change will not be accessible from other shells. It can be accomplished via the C API tzset or from the command line (my time zone used as example), export TZ=America/Chicago.

Alternatively, you can create a symbolic link called "/etc/localtime" that points to the appropriate time zone file in the "/usr/share/zoneinfo" directory. This is done with the C API symlink or from the command line, ln -sf /usr/share/zoneinfo/America/Chicago /etc/localtime. The -f option forces the link since it likely already exists.

If your application has access to the internet, rdate can be used to accurately update the system time.

Top comments (0)