Learn how time tracking is implemented from the hardware.
Time is a linear monotonically increasing value and to keep track of it, a system has to be powered to take note of every tick. For a microcomputer running an operating system that can go on and off, this means there is a need to constantly update time whenever the computer comes on, but that is not the case because of some intelligent mechanisms that computer hardware and operating systems use to keep track of the current time.
Real-Time Clock
A Real-Time Clock (RTC) is an electronic hardware component that helps track the current time and date, even when the system is powered off.
How it works
RTC uses an oscillator that generates a stable and precise frequency, typically 32.768 kHz. The pulses from the oscillator are sent to counters within the RTC chip where seconds, minutes, hours, days, and so on are measured. These counters increment to keep track of the current time and date. The values for the current date and time are stored in registers contained within the RTC chipset, these registers also help to keep track of configuration values such as alarms, enabling and disabling the clock, and adjusting for leap years.
RTC chips can be powered by a CMOS RAM battery but are mostly powered internally by an alternate power source, usually a replaceable lithium battery or modern supercapacitors.
Network Time Protocol
Although RTC can keep track of time using oscillators, there is no source of truth for what the current time might be.
NTP is a protocol designed to synchronize the clocks of computers over a network. It aims to keep the system time in sync with more accurate time sources, such as atomic clocks or GPS clocks. It implements the intersection algorithm and uses a client-server model to send time stamps which is accurate to 10 milliseconds over the public internet.
RTC and NTP
As mentioned earlier, time is monotonically increasing, operating systems use a combination of RTP and NTP to maintain a consistent time that users see.
On Windows, support for NTP is inbuilt can be configured through the system settings or the command line, and is managed by Windows Time service. This service can be manually started with:
$$
net start w32time
$$
On Linux, support for NTP is also built-in, but can be installed manually:
$$
sudo apt-get install ntp # Debian/Ubuntu
sudo yum install ntp # CentOS/RHEL
sudo dnf install ntp # Fedora
$$
And can be started as a daemon afterwards:
$$
sudo systemctl enable ntp
sudo systemctl start ntp
$$
RTC on mobile devices
For devices that do not have any networking support but can send and receive radio signals, there is a Radio-based RTC that mobile network providers use to send current time to mobile devices. This can explain why time is always correct on mobile devices even in remote areas without access to the internet.