Skip to content
hector@hcmc:~/blog/computer-store-time

How Computers Store and Manage Time

$ cat ~/blog/computer-store-time.mdx

How Do Computers Store Time?

  • Unix Time (Epoch Time)
  • System Time
  • File System Timestamps
  • Network Time Protocol (NTP)
  • Binary-Coded Decimal (BCD)
  • System BIOS/UEFI Time

Unix Time (Epoch Time)

UNIX timestamp: the number of seconds that have elapsed since 1970-01-01 00:00:00 UTC.

  • Example:
    • Timestamp in seconds: 1695718262
    • Timestamp in milliseconds: 1695718262342
  • Facts:
    • In older 32-bit systems, the signed integer will overflow in 2038.
    • Why 1970? The Unix OS was created in the late 1960s and early 1970s. Unix engineers arbitrarily selected 1970.

Datetime Format

FormatExample
ISO 86012023-09-25T16:20:52+07:00, 2023-09-25T09:20:52Z (Z = +00:00)
Vietnam26/09/2023
RFC 2822Mon, 25 Sep 2023 09:16:58 +0000
JavaScriptYYYY-MM-DDTHH:mm:ss.sssZ
JavaTue Sep 26 16:05:37 ICT 2023 (+0700)

See also: RFC 3339

When to Use Datetime vs. Timestamp?

  • Timestamp: records a (more or less) fixed point in time.
    • Example: created_at
  • Datetime: time can be set and changed arbitrarily.
    • Example: scheduled time for appointments

Best Practices

  • Backend uses the UTC time zone + ISO 8601 / timestamp.
  • Frontend uses local datetime (show the time zone).
  • DB stores values as timestamps if possible.
  • Store datetime with time zone.
  • MySQL: use fractional seconds for accuracy.
  • JVM time zone ≠ OS time zone.

Be Careful With

  • Time zone
  • Datetime format
  • Fractional seconds