Time Calculation by Computers – How It Works

real timetime

I need to add a certain feature to a module in a given project regarding time calculation. For this specific case I'm using Java and reading through the documentation of the Date class I found out the time is calculated in milliseconds starting from January 1, 1970, 00:00:00 GMT. I think it's safe to assume there is a similar "starting date" in other languages so I guess the specific implementation in Java doesn't matter.

How is the time calculation performed by the computer? How does it know exactly how many milliseconds have passed from that given "starting date and time" to the current date and time?

Best Answer

I think it's safe to assume there is a similar "starting date" in other languages so I guess the specific implementation in Java doesn't matter.

Pretty much all computers use this or a similar variation of Unix time.

How is the time calculation performed by the computer? How does it know exactly how many milliseconds have passed from that given "starting date and time" to the current date and time?

Typically, a computer includes one or more hardware devices that count time, usually based on a crystal oscillator (the same as used in most modern clocks). There are serveral variations/standards for such devices:

These timer devices usually have a separate battery that allows them to continue running when the computer is switched off. The computer interacts with them in two ways:

  • When it boots up, it reads the current time from the device
  • At regular intervals, the device causes a hardware interrupt that is handled by the OS to do any time-dependant tasks.

However, the crystal oscillators used in the hardware timers have limited precision and over time drift away from the correct time. For applications where it's important to have an accurate clock (or just to avoid the hassle of having to manually adjust it), computers regularly synchronize their time via the Network Time Protocol with a time server, which is connected (directly or indirectly) to a high-precision atomic clock.

Related Topic