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:
- On Linux boot, system clock is synced to hardware clock via script in
- System clock is used to keep time while OS is running
- On shutdown, hardware clock is synced to system clock
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 --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 --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.
hwclockyields the current hardware time in local time even if the
--utcoption is used.
/sbin/hwclockis 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
/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
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
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),
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.
check more on how to change timezone in Linux